package reflectDemo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
public class IntroSpectorTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3, 5);
System.out.println(BeanUtils.getProperty(pt1, "X")); //改行报异常 //.getClass().getName()
//以字符串的形式对属性进行操作,因为在web开发过程中,浏览器对数据的操作都是以字符串的形式进行的
BeanUtils.setProperty(pt1, "X", "9");
System.out.println(pt1.getX()); //这里将pt1类看做一个普通的类。
//"123"是一个毫秒值,如果在ReflectPoint类中没有实例化Date,这里会报空指针异常。
BeanUtils.setProperty(pt1, "birthday.time", "123");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));
PropertyUtils.setProperty(pt1, "X", 9); //该工具是以属性的真实类型对属性进行操作
System.out.println(PropertyUtils.getProperty(pt1, "X"));
}
}
//ReflectPoint类
package reflectDemo;
import java.util.Date;
class ReflectPoint {
public int x = 3;
public int y = 5;
private Date birthday = new Date();
public ReflectPoint(){}
public ReflectPoint(int x, int y)
{
this.x = x;
this.y = y;
}
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;
}
public String toString() {
return "ReflectPoint [x=" + x + ", y=" + y + "]";
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
|