gpt4 book ai didi

java - BeanInfo :methodDescriptors and class:declaredMethods : multiple methods with same name and method masking 之间的差异

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:36:54 25 4
gpt4 key购买 nike

当试图在运行时为某些属性获取 JPA 注释时,我遇到了这个问题。我无法解释为什么。

PS:在使用Spring进行调试后,我找到了这个问题的解释:编译器在编译时引入的桥接方法。请看我自己对这个问题的回答..

这是一个复制问题的示例源代码(真实代码的简化版本)。

导入java.beans.BeanInfo;导入 java.beans.IntrospectionException;导入 java.beans.Introspector;导入 java.beans.MethodDescriptor;导入 java.io.Serializable;导入 java.lang.reflect.Method;

公共(public)类方法掩码{

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 中有 2 个方法描述符用于 setId 而只有一个用于 getId ?
为什么在声明的方法中有 2 个 getId 方法和 2 个 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 接口(interface)中使用泛型......

这样声明,问题就消失了:不再有重复的方法。

public interface HasId  {
void setId(Long id);
Long getId();
}

public interface Storeable extends HasId {}

最佳答案

这是因为编译器在使用泛型时引入了桥接方法:
some explanation here

关于java - BeanInfo :methodDescriptors and class:declaredMethods : multiple methods with same name and method masking 之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6954586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com