2014-01-28 162 views
0

我浏览过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或者使用抽象类来获取类型信息。 我想联想TFoogetObject方法为Bar<Foo>对象。

有人认为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 

也许这就是你正在寻找的。 TypeToken和Invokable来自Google Guava。

€:修复了关于@PaulBellora的注释的代码

+0

请注意,新的TypeToken >(){}'很好 - 类标记构造函数用于解析类型参数,例如'new TypeToken (objectOfClassThatResolvesT.getClass()){}'。 –

+0

@ m0ep谢谢。这解决了我的问题。 –

+0

这将如何工作的静态方法在http://stackoverflow.com/q/30109459/2103767 – bhantol