假設我有一個簡單的類:如何檢查類是否有方法添加的方法?
public class TestClass {
/*...*/
}
我創建了注入了新的方法,這個類的一個方面:
public aspect TestAspect {
public void TestClass.aspectMethod() {
/*...*/
}
}
現在,我怎麼能檢查是否TestClass
已經TestAspect
在運行時添加的方法?
假設我有一個簡單的類:如何檢查類是否有方法添加的方法?
public class TestClass {
/*...*/
}
我創建了注入了新的方法,這個類的一個方面:
public aspect TestAspect {
public void TestClass.aspectMethod() {
/*...*/
}
}
現在,我怎麼能檢查是否TestClass
已經TestAspect
在運行時添加的方法?
最簡單的方法是簡單地在類反映:
TestClass.class.getDeclaredMethod("aspectMethod")
將拋出NoSuchMethodException,如果它不存在。或者如果你有字節,你可以使用字節碼訪問器來檢查字節碼中存在哪些方法 - 但是反射路由會少一些。
安迪的回答是正確的,我只是想回答的評論你的後續問題:
鴨打字不是Java的功能,但如果你用ITD爲了使類實現的接口,然後有一個您的縱橫擴展類的實例,您可以使用instanceof MyInterface
來確定您需要知道的內容。其他方式(也使用反射)也可用:
接口與方法,要通過ITD以後添加:
package de.scrum_master.app;
public interface MyInterface {
void myMethod();
}
樣品驅動器應用:
package de.scrum_master.app;
import java.lang.reflect.Type;
public class Application {
public static void main(String[] args) {
Application application = new Application();
// Use an instance
System.out.println(application instanceof MyInterface);
System.out.println(MyInterface.class.isInstance(application));
// Use the class
for (Type type : Application.class.getGenericInterfaces())
System.out.println(type);
for (Class<?> clazz : Application.class.getInterfaces())
System.out.println(clazz);
}
}
看點:
package de.scrum_master.aspect;
import de.scrum_master.app.Application;
import de.scrum_master.app.MyInterface;
public aspect MyAspect {
declare parents : Application implements MyInterface;
public void Application.myMethod() {}
}
應用輸出:
true
true
interface de.scrum_master.app.MyInterface
interface de.scrum_master.app.MyInterface
簡單但不錯的方法,kriegaex。我覺得這比Andy的回答更「自然」一點。 – Kao
呀,看來,這將是最簡單的方法。我認爲有一些非反射語言功能可以做到這一點。 Duck打字對於AspectJ中的類型間聲明非常有用。 – Kao