无法使用Reflection通过子类实例查看抽象基类方法

时间:2015-10-08 03:37:07

标签: java spring reflection

我有一个如下所示的抽象基类和一个扩展基类的子类。现在,当我通过spring获取子类的实例时,虽然我所有的基类方法都无法看到基类方法是公共的。 我试图获取通过spring检索到的对象(bean)的所有方法 我没有看到我的抽象基类中定义的方法。是否有人让我知道这段代码有什么问题?

我只能看到那些在子类中明确定义的方法。

//Base abstract class 
    public abstract class A<K, V> implements C<K, V>,CD<K,V> {
       public final V get(final K key){}
       public final V get(String key){}
       public String getValue();

    }
    //Child concrete class 
    public class Q extends A<Long, XYZ> implements QC,
        CD<Long, XYZ> {
     public Class<XYZ> getClass() {}
     public String getValue(){}
    }
    //Code to retrieve the objects using reflection
    final Object someObject = ApplicationContext.getBean("Q");

          for (Method method : someObject.getClass().getDeclaredMethods()) {
                        if (Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0
                            && method.getReturnType() != void.class
                            && (method.getName().startsWith("get") || method.getName().startsWith("is"))) {
                            Object value = method.invoke(someObject);
                            if (value != null) {
                                System.out.println(method.getName() + "=" + value);
                            }
                        }
                    }

2 个答案:

答案 0 :(得分:-1)

通常只查看您调查的类的方法,因为Class-Object只包含类本身的信息而不包含其父类的信息。如果要查看超类的字段和方法,则必须获取超类。

Class currentClass = someObject.getClass();
while (currentClass != null) {

   for (Method method : currentClass.getDeclaredMethods()) {
     ...
   }

   currentClass = currentClass.getSuperclass();
    //http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getSuperclass()

}

答案 1 :(得分:-1)

我发现了问题。问题在于理解这两种方法之间的区别,并根据您的需要使用它

1.Class.getDeclaredMethods()返回您尝试通过类对象引用的类的方法 2. Class.getMethods()返回您尝试引用的类的继承方法+方法。简而言之,它将返回其父类的所有方法或它正在实现的任何接口。由于getMethods采用客户端的类视图,该数组将包含所有公共方法,包括类本身中定义的方法并且在它的超级类和超级duper类中依此类推到Object

所以在我的情况下使用getMethods()修复了问题

相关问题