2011-08-04 83 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

哇,我不知道 –