/**
* 设计思路:设计一个模拟题目要求的JavaBean类,通过反射进行对其中的未知属性名的变量赋值。
*
* 建立模拟JavaBean类
* */
public class JavaBean {
//成员变量
private String itCast;
private int num;
private boolean flag;
private double money;
public String getItCast() {
return itCast;
}
public void setItCast(String itCast) {
this.itCast = itCast;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
public class Assign {
public static void main(String args[]) throws Exception, Exception{
Class<JavaBean> clazz = JavaBean.class; //拿到字节码
Object obj = clazz.newInstance(); //拿到字节码的一个对象实例
//通过字节码拿到BeanInfo实例对象
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
//通过BeanInfo拿到这个字节码的所有属性描述
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
//通过Pds拿到属性对应的set和get方法,并通过set方法进行赋值
for(PropertyDescriptor pd:pds){
Method setMethod = pd.getWriteMethod();
Method getMethod = pd.getReadMethod();
//拿到当前属性的类型字节码
Class<?> propertyClass = pd.getPropertyType();
//通过字节码来筛选出相应的属性,再对应赋值
if(propertyClass==String.class){
setMethod.invoke(obj, "www.itheima.com");
//打印get查看赋值结果
System.out.println(getMethod.invoke(obj));
}else if(propertyClass==int.class || propertyClass==Integer.class){
setMethod.invoke(obj, 100);
System.out.println(getMethod.invoke(obj));
}else if(propertyClass==Boolean.class || propertyClass==boolean.class){
setMethod.invoke(obj, true);
System.out.println(getMethod.invoke(obj));
}else if(propertyClass==Double.class || propertyClass==double.class){
setMethod.invoke(obj, 0.01D);
System.out.println(getMethod.invoke(obj));
}
}
}
}
|