【问题标题】:Multiple methods via reflection when implementing a method with generic return type实现具有通用返回类型的方法时通过反射的多个方法
【发布时间】:2014-06-11 17:03:35
【问题描述】:

当实现具有泛型返回类型的方法并在实现类上反射声明的方法时,反射 API 返回两个方法。例如:

interface Referenceable<T> {
    T getReference();
}

class UUIDRef implements Referenceable<UUID> {
    public UUID getReference() {
      System.out.println("You called");
      return null;
    }
}

@Test
public void test() throws Exception {
    UUIDRef ref = new UUIDRef();
    for (Method m : UUIDRef.class.getDeclaredMethods()) {
      System.out.println(String.format("%s %s", m.getReturnType(), m.getName()));
      m.invoke(ref, null);
    }
}

这个输出:

class java.util.UUID getReference You called class java.lang.Object getReference You called

为什么在UUIDRef 上声明了两种方法?有什么方法可以准确地了解两者中哪一个是最精致的,实际上已经在UUIDRef 上声明过?

【问题讨论】:

  • 你有没有尝试在实现的方法中添加@Override注解?
  • 我实际上是针对 1.5 编译的,这里不允许使用 @Override。

标签: java generics reflection


【解决方案1】:

为了支持协变返回类型,a bridge method must be created 能够在代码中调用需要声明的返回类型的方法。

简而言之,这个桥接方法就是在以下场景中调用的方法,其中T被擦除为Object

public <T> T doSomething(Referenceable<T> obj) {
   return obj.getReference();
}

使用m.isBridge() 来判断哪个是桥接方法。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
相关资源
最近更新 更多