----------------------
ASP.Net+Android+IOS开发、
.Net培训、期待与您交流! ----------------------
以上这些方式使用起来都比较的麻烦,当有这个需要的时候, 我们通常使用开源的工具BeanUtils 它能够提供很多的静态方法,很方便使用,这里就不做介绍了
1、关于javabean
什么是javabean?
一句话: 就是只能通过get set方法访问一个类的成员的类。 它主要是用于传递数据信息。
下面来演示一个javabean
import java.util.Date;
public class ReflectPoint {
private Date birthday = new Date();
private int x;
public int y;
//快捷键生成的构造函数 Alt+Shift+S 然后选择 Constructor using fields
public ReflectPoint(int x, int y) {
super();
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;
}
}
下面,是要对这个javabean进行内省的操作,要知道的是,在获取变量名之前我是不知道这个变量叫什么的,所以我用一个x来代替它,参考命名规则
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class IntroSpectorTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3, 5);
String propertyName = "x";
//下面是对javaBean的简单内省操作
Object retVal = getProperty(pt1, propertyName);//我选中那些代码然后用refactor 里面的抽取方法,把他们抽成了一个方法
System.out.println(retVal);
}
//这个本来是自动生成的方法
private static Object getProperty(ReflectPoint pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
/* 取x的值
PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass()); //创建一个属性描述的实例
Method methodGetX = pd.getReadMethod();//获得javaBean中用于读取属性值的方法
Object retVal = methodGetX.invoke(pt1, null);//直接调用它里面的get方法得到那个数值,注意这个方法没参数所以为null
*/
//这个方法是使用的一种比较复杂的方式
BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());//在javaBean上进行内省
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor pd : pds){
if(pd.getName().equals(propertyName))
{
Method methodGetX = pd.getReadMethod();
retVal = methodGetX.invoke(pt1);
break;
}
}
}
}
那么如何去对值进行设置呢? 下面就是对x的值进行重新设置
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class IntroSpectorTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3, 5);
String propertyName = "x";
//下面再调用set方法
Object value = 7;
setProperty(pt1, propertyName, value);
System.out.println(pt1.getX());
}
//这是设置x的值
private static void setProperty(ReflectPoint pt1, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, pt1.getClass()); //创建一个属性描述的实例
Method methodSetX = pd2.getWriteMethod(); //获得用于设置属性值的set方法
methodSetX.invoke(pt1, value);//重新设置x值
}
}
以上这些方式使用起来都比较的麻烦,当有这个需要的时候, 我们通常使用开源的工具BeanUtils 它能够提供很多的静态方法,很方便使用,这里就不做介绍了
---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ------------------