2011-08-04 23 views
2

是否可以访问以下行中的泛型参数?访问返回类型的泛型参数

public List<StoryLikeRef> getLikes() throws IOException 

我的意思是通过反射从返回类型中获取StoryLikeRef?

感谢

回答

10

是的,你可以假设StoryLikeRef是一个具体类型(而不是类型参数本身)。使用Method.getGenericReturnType可获得Type。示例代码:

import java.lang.reflect.*; 
import java.util.*; 

public class Test { 

    public List<String> getStringList() { 
     return null; 
    } 

    public List<Integer> getIntegerList() { 
     return null; 
    } 

    public static void main(String[] args) throws Exception { 
     showTypeParameters("getStringList"); 
     showTypeParameters("getIntegerList"); 
    } 

    // Only using throws Exception for sample code. Don't do 
    // this in real life. 
    private static void showTypeParameters(String methodName) 
     throws Exception { 
     Method method = Test.class.getMethod(methodName); 
     Type returnType = method.getGenericReturnType(); 
     System.out.println("Overall return type: " + returnType); 
     if (returnType instanceof ParameterizedType) { 
      ParameterizedType type = (ParameterizedType) returnType; 
      for (Type t: type.getActualTypeArguments()) { 
       System.out.println(" Type parameter: " + t); 
      } 
     } else { 
      System.out.println("Not a generic type"); 
     } 
    } 
} 
+0

哇,我不知道 –