2012-03-20 141 views
0

是否可以通过反射从非泛型类获取泛型(参数化)方法? 这里是什么,我想做一个示例: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(); 
     } 
    } 
} 

如果我运行泛型,我得到:

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

谢谢大家

回答

7

.getDeclaredMethod()应该用来代替.getMethod(),它只返回公共的。

+0

谢谢,就是这样!我太专注于类型擦除,因为注意到它只是一个可见性的问题:) – lencinhaus 2012-03-20 11:59:47