当我试图在运行时为一些属性获取JPA注释时,我遇到了这个问题。我不能解释为什么。
PS:在与Spring进行了一次调试会话之后,我找到了这个问题的解释:编译器在编译时引入的桥接方法。请看我自己对这个问题的回答。
以下是复制该问题的示例源代码(真实代码的简化版本)。
导入java.beans.BeanInfo;导入java.beans.IntrospectionException;导入java.beans.Introspector;导入java.beans.MethodDescriptor;导入java.io.Serializable;导入java.lang.reflect.Method;
公共类MethodMasking {
public interface HasId<ID extends Serializable> {
void setId(ID id);
ID getId();
}
public interface Storeable extends HasId<Long> {}
class Item implements Storeable {Long id; String code;
Item(Long id, String code) { this.id = id; this.code = code; }
public Long getId() { return id; }
public void setId(Long id) {this.id = id;}
}
public static void main(String[] args) throws IntrospectionException {
final BeanInfo beanInfo = Introspector.getBeanInfo(Item.class);
java.lang.System.out.println("BeanInfo:methodDescriptors:");
final MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
for (MethodDescriptor methodDescriptor : methodDescriptors) {
java.lang.System.out.println("\t"+methodDescriptor.getMethod().getName());
}
java.lang.System.out.println("class:declaredMethods:");
final Method[] declaredMethods = Item.class.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
java.lang.System.out.println("\t"+declaredMethod.getName());
}
}
}程序输出:
BeanInfo:methodDescriptors:
hashCode
wait
getId
notifyAll
equals
wait
wait
toString
setId
notify
setId
getClass
class:declaredMethods:
getId
getId
setId
setId
现在我很困惑:
为什么在beanInfo中有两个用于setId的方法描述符,而只有一个用于getId的方法描述符?
为什么在声明的方法中有两个用于getId的方法和两个用于setId的方法?
在调试过程中,我在使用getDeclaredMethods时有了这些方法签名:
[0] = {java.lang.reflect.Method@139}"public java.lang.Long MethodMasking$Item.getId()"
[1] = {java.lang.reflect.Method@446}"public java.io.Serializable MethodMasking$Item.getId()"
[2] = {java.lang.reflect.Method@447}"public void MethodMasking$Item.setId(java.lang.Long)"
[3] = {java.lang.reflect.Method@448}"public void MethodMasking$Item.setId(java.io.Serializable)"
编辑:经过一些测试,我发现问题的原因是在HasId接口中使用了泛型……
以这种方式声明,问题就消失了:不再有重复的方法。
public interface HasId {
void setId(Long id);
Long getId();
}
public interface Storeable extends HasId {}
发布于 2011-08-16 08:42:20
这是因为当使用泛型时,编译器引入了桥方法:
发布于 2011-08-05 10:10:53
打印出有关您接收的方法的更多信息:不仅是它们的名称,还包括参数列表。尝试有足够的信息来区分重载和平均负载。不同之处可能来自于此,但对我来说还不是很清楚。
问候你,斯特凡
https://stackoverflow.com/questions/6954586
复制相似问题