【问题标题】:Why does reflection return two methods, when there is only one implementation?当只有一种实现时,为什么反射会返回两种方法?
【发布时间】:2013-04-27 23:22:57
【问题描述】:

假设我有这个代码:

public interface Address {
    public int getNo();
}

public interface User<T extends Address> {
    public String getUsername();
    public T getAddress();    
}

public class AddressImpl implements Address {
    private int no;
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
}

public class UserImpl implements User<AddressImpl> {
    private String username;
    private AddressImpl addressImpl;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public AddressImpl getAddress() {
        return addressImpl;
    }

    public void setAddress(AddressImpl addressImpl) {
        this.addressImpl = addressImpl;
    }
}

运行代码:

int getAddressMethodCount = 0;
for (Method method : UserImpl.class.getMethods()) {
    if (method.getName().startsWith("getAddress")) {
        getAddressMethodCount++;
    }
}

对于getAddressMethodCount 变量将产生 2;为什么会这样?

【问题讨论】:

  • 我很喜欢。我每天都在发现新事物。

标签: java generics inheritance reflection


【解决方案1】:

这是协变返回类型的实现方式。 javap -private 会比反射更方便地展示给你。

具有合成桥接方法的子类处理转发到更具体的方法。就 JVM 而言,方法具有名称、原始类型参数序列和原始类型返回。您可以重载字节码中的返回类型。

System.err.println(mehtod.getReturnType()); 应该为您提供两种方法的不同结果。

【讨论】:

  • 我班上哪一个?
  • 他们都在你的班级。查询方法的返回类型将显示一个方法返回地址,而另一个方法,即 Tom 上面提到的合成桥,将返回您的 AddressImpl 类型。
  • +1 大概调用isSynthetic 将在一个Methodfalse 上返回true
  • @PaulBellora 是的,还有isBridgejavap -v 将显示 ACC_BRIDGE, ACC_SYNTHETIC 标志。
猜你喜欢
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 2010-11-20
  • 2015-05-01
  • 2015-03-24
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
相关资源
最近更新 更多