2017-02-16 7 views
1

を使用して、メソッドの戻り値を入力ガイド:は、Javaのリフレクション

class Test { 
    Thing<String> getThing(String thing) {} 
} 

どのように私はString.classは、テストのインスタンスにリフレクションを使用して確認できますか? 私が受けたいパスは、新しいTest() - >クラスを取得 - メソッドを見つける - >戻り値の型を取得 - > - >何とかString.classを取得しますが、最後の部分がどのように行われたかはわかりません。私は今まで私がThing<java.lang.String>を取得していますが、内部クラスは取得していません。 .getReturnType()一方

import org.reflections.ReflectionUtils; 

Iterables.getOnlyElement(ReflectionUtils.getAllMethods((new Test()).getClass())).getGenericType(); 

だけでは、標準のリフレクションAPI(ReflectionUtilsを使用する必要はありません)を使用して、それを得ることができJavaでは私Thing.class ...

+1

[型消去](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)。 –

+0

ok、私はそれを使用する方法を見ていません – mathematician

+0

ジェネリック型でない場合、それは常に – mathematician

答えて

1

を取得します。 getGenericReturnTypeを正しく使用しました。あなただけParameterizedTypeにキャストする必要があります。

public static void main(String[] args) throws NoSuchMethodException { 
    Method m = Test.class.getDeclaredMethod("getThing", String.class); 
    Type type = m.getGenericReturnType(); 
    // type is Thing<java.lang.String> 
    if(type instanceof ParameterizedType) { 
     Type[] innerTypes = ((ParameterizedType) type).getActualTypeArguments(); 
     if(innerTypes.length == 1) { 
      Type innerType = innerTypes[0]; 
      if(innerType instanceof Class) { 
       // innerType is java.lang.String class 
       System.out.println(((Class<?>) innerType).getName()); 
      } 
     } 
    } 
} 
+0

完璧!ありがとう! – mathematician

+0

@mathhemian実際にはもっと簡単です(Java 1.5でも動作します)、更新された答えを確認してください。 –

関連する問題