类型转换之 PropertyEditorSupport类

这个类可以用于自定义的类型转换, 子类继承这个类之后可以重写子类的方法 ,其中比较重要的是setAsText和setValue方法,setAsText 子自己的方式处理转换,setValue将转换的结果进行保存,最后调用getValue()获取转换后的结果

 

例子如下

将三个字符串转换为userInfo对应的属性

  

public class userInfo {
private long userId;
private String username;
private int age;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}

 

//进行转换的类

public class userPropertyEdit extends PropertyEditorSupport {

@Override
public void setAsText(String s) {
// super.setAsText(info);
// String[] personInfo = StringUtils.delimitedListToStringArray(info, "|");
// 顺序为 id,age,name
String[] Info = {"1","2","lile"};
userInfo man = new userInfo();
man.setUserId(Integer.parseInt(Info[0]));
man.setAge(Integer.parseInt(Info[1]));
man.setUsername(Info[2]);
setValue(man);
}

}

 

//测试类

package myrefelct;

public class testProperty {
public static void main(String[] args) {
userPropertyEdit e = new userPropertyEdit();
e.setAsText("");
Object s = e.getValue();
System.out.println(s);
}

}

 

posted on 2014-11-24 17:43  李乐已存在  阅读(1015)  评论(0编辑  收藏  举报

AmazingCounters.com