小编len*_*aus的帖子

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

是否有可能通过反射从非泛型类中获取通用(参数化)方法?这是我想要做的样本:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我运行Generics,我得到:

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

谢谢大家

java generics reflection

0
推荐指数
1
解决办法
499
查看次数

标签 统计

generics ×1

java ×1

reflection ×1