【发布时间】:2015-07-18 12:30:49
【问题描述】:
我在 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。 -
是的,我知道。有没有办法使用
TypeToken或类似方法获取我正在寻找的信息来获取getObject方法的实际返回类型? -
它没有。曾经。时期。您无法检索它。
-
您还没有展示哪些代码在运行时失败或如何失败。
-
@JigarPatel 请编辑问题以准确提供演示问题的代码,如果抛出异常堆栈跟踪。
标签: java generics reflection