java - 泛型作为方法返回类型

标签 java generics reflection

我在 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或者使用抽象类来获取类型信息。 我要关联 TFoo对于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/

相关文章:

c# - 从 property 属性获取数据

JAVA:将 String 转换为(动态已知的)原始类型以实例化(动态已知的)类

Java 日历返回错误的月份

java - 如何在 Android 中为动态选择的图像创建 savedInstanceState?

java - 授予互联网权限后 WebView 未加载?

C# 泛型工厂方法

java - 具有 hibernate 和超时等待空闲对象异常的tomcat数据源

java - System.arraycopy() 抛出越界异常

Java 未绑定(bind)通配符泛型

.net - 检查属性是否为 bool 类型