【问题标题】:Generic as method return type泛型作为方法返回类型
【发布时间】: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&lt;Foo&gt; 对象。

有些人认为 java 不保留通用信息。在那种情况下,为什么第一次施法有效而第二次施法无效。

Object fooObject = new Foo();
bar.setObject((Foo) fooObject); //This works
Object object = 12;
bar.setObject((Foo) object); //This throws casting error

感谢任何帮助。

【问题讨论】:

  • 你明白编译器会丢弃所有类型参数,对吧?在运行时,Bar&lt;Foo&gt; 只是 Bar
  • 是的,我知道。有没有办法使用TypeToken 或类似方法获取我正在寻找的信息来获取getObject 方法的实际返回类型?
  • 它没有。曾经。时期。您无法检索它。
  • 您还没有展示哪些代码在运行时失败或如何失败。
  • @JigarPatel 请编辑问题以准确提供演示问题的代码,如果抛出异常堆栈跟踪。

标签: java generics reflection


【解决方案1】:
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 评论的代码

【讨论】:

  • 请注意 new TypeToken&lt;Test.Bar&lt;Foo&gt;&gt;() {} 很好 - 类令牌构造函数用于解析类型参数,例如new TypeToken&lt;T&gt;( objectOfClassThatResolvesT.getClass() ) {}.
  • 这对于stackoverflow.com/q/30109459/2103767中的静态方法如何工作
猜你喜欢
  • 2016-12-24
  • 1970-01-01
  • 2014-09-08
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多