2014-01-28 2 views
0

내가 직면하고있는 문제에 대한 대답을 찾으려면 StackOverflow를 둘러 보았습니다. 나는 많은 좋은 해답을 보았지만 아직도 나의 질문에 답하지 않는다. 그래서 여기일반 메서드 반환 형식

http://gafter.blogspot.com/search?q=super+type+token

http://qussay.com/2013/09/28/handling-java-generic-types-with-reflection/

Java generics: get class of generic method's return type

How to find the parameterized type of the return type through inspection?

Get type of a generic parameter in Java with reflection

는 내가하고 싶은 것입니다. Reflection을 사용하여 모든 메서드와 그 반환 형식 (일반이 아닌)을 가져 오려고합니다. 이렇게하려면 Introspector.getBeanInfo을 사용했습니다. 그러나 반환 유형을 알 수없는 메서드를 실행하면 제한이 발생합니다.

public class Foo { 

    public String name; 

    public String getName() { 
     return name; 
    } 

    public void setName(final String name) { 
     this.name = name; 
    } 
} 

public class Bar<T> { 

    T object; 

    public T getObject() { 
     return object; 
    } 

    public void setObject(final T object) { 
     this.object = object; 
    } 
} 

@Test 
    public void testFooBar() throws NoSuchMethodException, SecurityException, IllegalAccessException, 
      IllegalArgumentException, InvocationTargetException { 

     Foo foo = new Foo(); 
     Bar<Foo> bar = new Bar<Foo>(); 
     bar.setObject(foo); 
     Method mRead = bar.getClass().getMethod("getObject", null); 

     System.out.println(Foo.class);// Foo 
     System.out.println(foo.getClass());// Foo 
     System.out.println(Bar.class);// Bar 
     System.out.println(bar.getClass());// Bar 
     System.out.println(mRead.getReturnType()); // java.lang.Object 
     System.out.println(mRead.getGenericReturnType());// T 
     System.out.println(mRead.getGenericReturnType());// T 
     System.out.println(mRead.invoke(bar, null).getClass());// Foo 
    } 

메서드 반환 유형 T이 일반인지 여부를 어떻게 알 수 있습니까? 런타임시 객체를 가질 수있는 여유가 없습니다. Google TypeToken을 실험 중이거나 추상 클래스를 사용하여 유형 정보를 가져 왔습니다. Bar<Foo> 개체의 경우 getObject 메서드의 경우 TFoo을 연결하고 싶습니다.

일부 사람들은 java가 일반 정보를 보존하지 않는다고 주장합니다. 이 경우 왜 첫 번째 주물이 작동하고 두 번째 주조가 작동하지 않습니다.

Object fooObject = new Foo(); 
bar.setObject((Foo) fooObject); //This works 
Object object = 12; 
bar.setObject((Foo) object); //This throws casting error 

도움을 주시면 감사하겠습니다.

+2

컴파일러가 모든 유형 매개 변수를 무시한다는 것을 알고 있습니까? 런타임에 'Bar '은'Bar '입니다. –

+0

네, 그 사실을 알고 있습니다. 'TypeToken' 또는 유사한 접근 방식을 사용하여 찾고있는 정보를 얻을 수있는 방법이 있나요? getObject 메소드의 실제 반환 유형을 얻으려면 어떻게해야합니까? –

+0

@ JigarPatel. 그래서 아닙니다, 당신은 다윗이 한 말을 이해하지 못합니다. –

답변

2
Bar<Foo> bar = new Bar<Foo>(); 
Method mRead = bar.getClass().getMethod("getObject", null); 
TypeToken<Bar<Foo>> tt = new TypeToken<Test.Bar<Foo>>() {}; 
Invokable<Bar<Foo>, Object> inv = tt.method(mRead); 
System.out.println(inv.getReturnType()); // Test$Foo 

어쩌면 이것이 당신이 찾고있는 것일 수 있습니다. 유형 토큰 및 인보 케블은 Google 구아바 출신입니다.

: @PaulBellora의 설명과 관련하여 코드가 수정되었습니다.

+0

'new TypeToken >() {}'은 괜찮습니다. 클래스 토큰 생성자는 타입 매개 변수를 해석하기위한 것입니다. '새로운 TypeToken (objectOfClassThatResolvesT.getClass()) {}'. –

+0

@ m0ep 감사합니다. 이것은 내 문제를 해결했다. –

+0

이 방법은 http://stackoverflow.com/q/30109459/2103767의 정적 메서드에서 어떻게 작동합니까? – bhantol