简体   繁体   English

Java反射-从非泛型类获取泛型方法

[英]Java reflection - get generic method from non-generic class

is it possible to get a generic (parametrized) method from a non-generic class through reflection? 是否可以通过反射从非泛型类中获取泛型(参数化)方法? Here's a sample of what i want to do: 这是我要执行的操作的一个示例:

public interface GenericInterface<T> {
    public T publicMethod(T arg);
}

public class NonGenericClassWithGenericMethods {
    private <T> void privateMethod(GenericInterface<T> arg) {

    }
}

public class Generics {
    public static void main(String[] args) {
        try {
            NonGenericClassWithGenericMethods.class.getMethod("privateMethod", GenericInterface.class).setAccessible(true);
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

If i run Generics, i get: 如果我运行泛型,我将得到:

java.lang.NoSuchMethodException: NonGenericClassWithGenericMethods.privateMethod(GenericInterface) java.lang.NoSuchMethodException:NonGenericClassWithGenericMethods.privateMethod(GenericInterface)

Thanks everybody 谢谢大家

.getDeclaredMethod()应改为使用的.getMethod()仅返回公共的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM