gpt4 book ai didi

java - 使用父类(super class)作为参数的类反射查找方法

转载 作者:行者123 更新时间:2023-11-30 09:18:01 26 4
gpt4 key购买 nike

关于一些我无法理解的小问题。我有以下内容:

public abstract class A 
{
...
}

和这个类的扩展

public class B extends A
{
...
}

现在我有一个如下所示的类

public class DoStuff extends AbstractDoStuff
{
public void doNiceStuff(B b)
{
...
}
}

我试图通过反射调用的是此类的方法。但是,我试图从不知道 B 而只知道 A 的包中调用此方法。这是由于项目的依赖性

所以我有以下代码需要找到方法 doNiceStuff(B):

public abstract class AbstractDoStuff
{
public static Method getGetterMethod(Class<? extends AbstractDoStuff> stuffClass) throws NoSuchMethodException
{
Method method = stuffClass.getDeclaredMethod("doNiceStuff", A.class)
...
}
}

所以 getDeclaredMethod 应该在类 DoStuff 上找到 doNiceStuff,但似乎反射无法找到使用父类(super class) A.class 的方法。但是我不能在那里提供 B.class,因为包对 B 的存在一无所知。

知道是否有办法解决这个问题吗?

问候

迈克尔

最佳答案

您可以使用更多反射来获取它:

Method[] methods = stuffClass.getMethods(); 
for(Method m: methods) {
if(m.getName().equals("doNiceStuff")) {
Class<?> paramTypes = m.getParameterTypes();

//condition on the desired parameter types comes here
if(paramTypes.length==1 && A.class.isAssignableFrom(paramTypes[0]) {
//we found it!
}

}
}

为什么 isSuperClass() 在这种情况下不好?

假设我们这样做:

if (paramTypes.length == 1 && paramTypes[0].getSuperclass().equals(A.class)) {
...

这个解决方案适用于 B 类,但是如果我们有一个 C 类呢?

public class C extends B {


public void doNiceStuff(C arg0) {
//do nice stuff here
}

}

这种情况

paramTypes[0].getSuperclass().equals(A.class)

会是假的! paramTypes[0].getSuperClass() 是 B.class,不等于 A.class...

Class.getMethods()

Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

Class.isAssignableFrom()

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false. Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.

推荐阅读:

关于java - 使用父类(super class)作为参数的类反射查找方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18737729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com