【发布时间】:2014-10-27 22:28:11
【问题描述】:
看看这段代码:
public class Main {
public class A {
public final void method() {}
}
public class B extends A {}
public static main() {
try {
Method method = B.class.getMethod("method");
//Returns the name of Main$A, but I want Main$B
System.out.println(method.getDeclaringClass().getName());
} catch (NoSuchMethodException e) {}
}
}
我正在尝试从我之前从子类中获取的继承方法中获取该类。这样做的原因是在我的应用程序中,我将具有指定注释的所有方法按对象存储到 Set<Method> 中,并将对象本身存储在 Map<Class<?>, Object> 中,以便以后轻松调用该方法。
我知道method.getDeclaringClass() 返回Main$A 是有意义的,因为这是声明它的地方,而不是Main$B,但我只是想知道是否有其他方法可以解决我的问题。
【问题讨论】:
-
什么问题?当您拥有子类的实例时,您将从子类中获得实现。这是设计使然。
-
@ElliottFrisch 我认为他们会使用
B.class进行查找。 -
@ElliottFrisch 我的子类 B 没有并且 不能 覆盖 A 中的方法;我将编辑问题以反映这一点。例如,我想将
B的实例存储在Map<Class<?>, Object>中,通过键Class<B>和方法method()存储在Set<Method>中,如我的应用程序中所述。这就是问题所在:稍后,我将尝试通过getDeclaringClass()方法(现在是Class<A>)将类从method()中取出。然后我会继续尝试通过该类将实例从我的地图中取出,并获得一个 NPE。 -
@Octopod 在填充
Map时您可以访问什么? -
只需创建一个包含
Method和所需Class的对象。您可能会认为该对象的正确hashCode为Method.hashCodeuses only the declaring class and the name,如果您的重载方法仅在参数类型上有所不同,则它在HashSet中的表现不佳......
标签: java inheritance reflection methods