我浏览过StackOverflow以找到我面临的问题的答案。我遇到了很多很好的答案,但仍然没有回答我的问题。泛型作为方法返回类型
Get type of a generic parameter in Java with reflection
How to find the parameterized type of the return type through inspection?
Java generics: get class of generic method's return type
http://qussay.com/2013/09/28/handling-java-generic-types-with-reflection/
http://gafter.blogspot.com/search?q=super+type+token
所以这是我想做的事情。 使用反射,我想获得所有的方法和它的返回类型(非泛型)。 我一直在使用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
或者使用抽象类来获取类型信息。 我想联想T
到Foo
为getObject
方法为Bar<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。所以不,你不明白大卫说什么。 –