JavaBean代码

来源:互联网 发布:不用网络的导航 编辑:程序博客网 时间:2024/05/16 00:53
package cn.itcast.day1;


import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;


import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;


public class IntroSpaceTest {


/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
ReflectPoint pt1=new ReflectPoint(3,5);

String properName="x";
//第一个参数properName为当作JavaBean类中属性的编程名称。
//第二个参数pt1.getClass()为目标 bean 的 Class 对象(字节码)
PropertyDescriptor pd=new PropertyDescriptor(properName,pt1.getClass());
//  获得应该用于读取属性值的方法。
Method methodGetX=pd.getReadMethod();
//从pt1对象身上获取相应属性值
Object retVal=methodGetX.invoke(pt1);
System.out.println(retVal);

//获得应该用于写入属性值的方法。
Method methodSetX=pd.getWriteMethod();
//将pt1对象身上相应属性值设置为7
methodSetX.invoke(pt1,7);
//使用工具包,简化操作代码
//获取对象属性
System.out.println(BeanUtils.getProperty(pt1, "x"));
System.out.println(pt1.getX());
//设置对象属性
BeanUtils.setProperty(pt1, "x", "9");
System.out.println(pt1.getX());
//支持属性的级联操作
BeanUtils.setProperty(pt1, "birthday.time", "111");
System.out.println(BeanUtils.getProperty(pt1,"birthday.time"));


PropertyUtils.setProperty(pt1, "x", 9);
System.out.println(PropertyUtils.getProperty(pt1, "x"));
}


}



package cn.itcast.day1;


import java.util.Date;


public class ReflectPoint {
private Date birthday = new Date();

private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";

public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}


@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}




@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}




@Override
public String toString(){
return str1 + ":" + str2 + ":" + str3;
}




public int getX() {
return x;
}




public void setX(int x) {
this.x = x;
}




public int getY() {
return y;
}




public void setY(int y) {
this.y = y;
}




public Date getBirthday() {
return birthday;
}




public void setBirthday(Date birthday) {
this.birthday = birthday;
}

}



分享一下我的学习资料!!!!
Java全套顶级视频
http://pro.net.itcast.cn/View-22-1435.aspx
DotNet全套视频
http://pro.net.itcast.cn/View-23-1435.aspx
PHP全套视频
http://pro.net.itcast.cn/View-24-1435.aspx
全世界最适合0基础学习编程的网上校园
http://pro.net.itcast.cn/View-25-1435.aspx
免费申请java全套视频光盘区域
http://pro.net.itcast.cn/View-26-1435.aspx


原创粉丝点击