내가 직면하고있는 문제에 대한 대답을 찾으려면 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
메서드의 경우 T
에 Foo
을 연결하고 싶습니다.
일부 사람들은 java가 일반 정보를 보존하지 않는다고 주장합니다. 이 경우 왜 첫 번째 주물이 작동하고 두 번째 주조가 작동하지 않습니다.
Object fooObject = new Foo();
bar.setObject((Foo) fooObject); //This works
Object object = 12;
bar.setObject((Foo) object); //This throws casting error
도움을 주시면 감사하겠습니다.
컴파일러가 모든 유형 매개 변수를 무시한다는 것을 알고 있습니까? 런타임에 'Bar'은'Bar '입니다. –
네, 그 사실을 알고 있습니다. 'TypeToken' 또는 유사한 접근 방식을 사용하여 찾고있는 정보를 얻을 수있는 방법이 있나요? getObject 메소드의 실제 반환 유형을 얻으려면 어떻게해야합니까? –
@ JigarPatel. 그래서 아닙니다, 당신은 다윗이 한 말을 이해하지 못합니다. –