[英]Why does reflection return two methods, when there is only one implementation?
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++;
}
}
would yield 2 for getAddressMethodCount
variable; getAddressMethodCount
变量将产生2; why is this so? 为什么会这样?
It's the way covariant return types are implemented. 这是协变返回类型的实现方式。
javap -private
will show you more conveniently than reflection. javap -private
会比反射更方便地向您展示。
The subclass with have a synthetic bridge method that handles forwarding to the more specific method. 具有合成桥接方法的子类处理转发到更具体的方法。 As far the JVM is concerned methods have a name, a sequence of raw typed parameters and a raw type return.
就JVM而言,方法有一个名称,一系列原始类型参数和一个原始类型返回。 You can overload on return type in bytecode.
您可以在字节码中重载返回类型。
A System.err.println(mehtod.getReturnType());
System.err.println(mehtod.getReturnType());
should give you different results for the two methods. 应该给你两种方法不同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.