2014-07-11 68 views
0

假设我有一个简单的类:如何检查类是否有方法添加的方法?

public class TestClass { 
    /*...*/ 
} 

我创建了注入了新的方法,这个类的一个方面:

public aspect TestAspect { 
    public void TestClass.aspectMethod() { 
     /*...*/ 
    } 
} 

现在,我怎么能检查是否TestClass已经TestAspect在运行时添加的方法?

回答

2

最简单的方法是简单地在类反映:

TestClass.class.getDeclaredMethod("aspectMethod") 

将抛出NoSuchMethodException,如果它不存在。或者如果你有字节,你可以使用字节码访问器来检查字节码中存在哪些方法 - 但是反射路由会少一些。

+0

呀,看来,这将是最简单的方法。我认为有一些非反射语言功能可以做到这一点。 Duck打字对于AspectJ中的类型间声明非常有用。 – Kao

1

安迪的回答是正确的,我只是想回答的评论你的后续问题:

鸭打字不是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 
+0

简单但不错的方法,kriegaex。我觉得这比Andy的回答更“自然”一点。 – Kao

相关问题