我在 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<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
也许这就是您正在寻找的东西。 TypeToken 和 Invokable 来自 Google Guava。
€:修复了与 @PaulBellora 评论相关的代码
关于java - 泛型作为方法返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21416108/