小编典典

通用方法返回类型

java

这就是我想要做的。使用反射,我想获取所有方法及其返回类型(非泛型)。我一直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到对象FoogetObject方法Bar<Foo>

有人认为Java不保留通用信息。在这种情况下,为什么第一次强制转换有效而第二次强制转换无效。

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

任何帮助表示赞赏。


阅读 159

收藏
2020-11-23

共1个答案

小编典典

Bar bar = new Bar();
Method mRead = bar.getClass().getMethod( “getObject”, null );
TypeToken> tt = new TypeToken>() {};
Invokable, Object> inv = tt.method( mRead );
System.out.println( inv.getReturnType() ); // Test$Foo

也许这就是您要搜索的。TypeToken和Invokable来自Google Guava。

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

2020-11-23