public interface IBusinessObject<PK extends Serializable> extends Serializable {
PK getPrimaryKey();
void setPrimaryKey(PK id);
}
PK getPrimaryKey();
void setPrimaryKey(PK id);
}
在我的子類中是這么實現(xiàn)的
public class Code implements IBusinessObject<Long>{
private Long primaryKey;
public void setPrimaryKey(Long id){
this.primaryKey=id;
}
public Long getPrimaryKey(){
return primaryKey
}
}
private Long primaryKey;
public void setPrimaryKey(Long id){
this.primaryKey=id;
}
public Long getPrimaryKey(){
return primaryKey
}
}
在通常的實例化過程中,是不會存在問題的。當時的問題是,我定義了另外一個類,用于引用Code
public class TestBean {
private Code code;
public void setCode(){
}
public Code getCode(){
}
}
private Code code;
public void setCode(){

public Code getCode(){

}
當在spring環(huán)境中時,使用spring的bind類處理的時候,發(fā)現(xiàn),我的code.primaryKey的類型居然為Serializable,而不是我想要的Long
當時以為其他地方搞錯了,寫了個簡單的測試代碼
TestBean b=new TextBean();
BeanWrapperImpl wrapper=new BeanWrapperImpl(b);
b.setPropertyValue("code.primaryKey","1");
assertTrue(b.getCode().getPrimaryKey() instanceof Long);
BeanWrapperImpl wrapper=new BeanWrapperImpl(b);
b.setPropertyValue("code.primaryKey","1");
assertTrue(b.getCode().getPrimaryKey() instanceof Long);
居然是失敗的。
只有在
b.setPropertyValue("code.primaryKey",new Long(1));
assertTrue(b.getCode().getPrimaryKey() instanceof Long);
assertTrue(b.getCode().getPrimaryKey() instanceof Long);
才成功。
仔細跟蹤,發(fā)現(xiàn)原來,泛型的時候,產生的編譯類中,有兩個同名的方法
public void setPrimaryKey(Long id){
this.primaryKey=id;
}
public Long getPrimaryKey(){
return primaryKey
}
和
public void setPrimaryKey(Serializable id){
this.primaryKey=id;
}
public Serializable getPrimaryKey(){
return primaryKey
}
this.primaryKey=id;
}
public Long getPrimaryKey(){
return primaryKey
}
和
public void setPrimaryKey(Serializable id){
this.primaryKey=id;
}
public Serializable getPrimaryKey(){
return primaryKey
}
而java.beans規(guī)范對于這種情況是沒有辦法分清楚,所以也就導致了結果和預期的不同。
如果是在程序中,這點算不了問題。可是我需要在web的頁面上進行值的綁定,而輸入的東西,只能為字符串。所以不可能出來Long類型。
目前,采用了一種比較傻的辦法,在TestBean中增加了一個臨時變量x,通過x向code傳值
如下:
public void setWsCode(String wsCode) {
this.wsCode = wsCode;
if (StringUtils.isNumeric(wsCode))
this.code.setPrimaryKey(NumberUtils.toLong(wsCode));
}
this.wsCode = wsCode;
if (StringUtils.isNumeric(wsCode))
this.code.setPrimaryKey(NumberUtils.toLong(wsCode));
}
不知道還有沒有其他好的解決方案。