當試圖在某些屬性的運行時獲得JPA批註時,我遇到了此問題。我無法解釋爲什麼。 PS:在與Spring進行調試會話後,我發現了這個問題的解釋:編譯器在編譯時引入的橋接方法。請參閱我自己對此問題的回答。BeanInfo:methodDescriptors和class之間的差異:declaredMethods:具有相同名稱和方法掩碼的多個方法
以下是複製問題(簡化版真實代碼)的示例源代碼。
import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.MethodDescriptor; import java.io.Serializable; import 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 2分方法的描述,但只有一個爲getId?
爲什麼在聲明的方法中有2個方法用於getId和2個方法用於setId?
在調試使用getDeclaredMethods時,我有這些方法的簽名:
[0] = {[email protected]}"public java.lang.Long MethodMasking$Item.getId()"
[1] = {[email protected]}"public java.io.Serializable MethodMasking$Item.getId()"
[2] = {[email protected]}"public void MethodMasking$Item.setId(java.lang.Long)"
[3] = {[email protected]}"public void MethodMasking$Item.setId(java.io.Serializable)"
編輯: 一些測試後,我發現,問題的原因是在HasId接口仿製藥的使用...
聲明這樣,問題消失:沒有更多的重複方法。
public interface HasId {
void setId(Long id);
Long getId();
}
public interface Storeable extends HasId {}
斯特凡嗨,什麼樣的附加信息會有所幫助? – Guillaume
重載的參數類型列表,比較爲重載繼承的方法。 – Snicolas
我發現問題的根源:HasId正在使用泛型。但我覺得這種行爲很奇怪。 – Guillaume