存在一个JavaBean,它包含以下几种可能的属性:
1:boolean/Boolean
2:int/Integer
3:String
4:double/Double
属性名未知,现在要给这些属性设置默认值,以下是要求的默认值:
String类型的默认值为字符串 www.csdn.com
int/Integer类型的默认值为100
boolean/Boolean类型的默认值为true
double/Double的默认值为0.01D.
只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现
{
private int id; //int variable.
private double salary; //double variable.
private String name; //String variable.
private boolean male = true; //boolean variable. public CsdnBean() //默认构造函数初始化.
{
id=100;
salary=0.01D;
name="www.csdn.com";
male=true;
} public int getId()
{
return id;
}
public void setId(int id)
{
this.id=id;
} public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
} public boolean isMale()//注意,不是getMale,而是isMale().
{
return male;
}
public void setMale(boolean male)
{
this.male=male;
} public double getSalary()
{
return salary;
}
public void setSalary(double salary)
{
this.salary=salary;
}
}
public class CsdnBean implements Serializable
package eclipse.test;public class JavaBean { boolean live = true;
int length = 100;
String net = "www.csdn.com";
double number = 0.01D; public boolean isLive() {
return live;
}
public void setLive(boolean live) {
this.live = live;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getNet() {
return net;
}
public void setNet(String net) {
this.net = net;
}
public double getNumber() {
return number;
}
public void setNumber(double number) {
this.number = number;
}
}写完了才发现和一楼的哥们写的一样,就该就是这么写的吧
PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors;//获得JavaBean的所有属性描述
for(PropertyDescriptor pd:pds){
Method readMethod=pd.getWriteMethod();//获得当前迭代属性的set方法
Class propClass=pd.getPropertyType();//获得当前迭代属性的类型
if(propClass==String.class)//如果是String类型设置为www.csdn.com
readMethod.invoke(javaBean,"www.csdn.com");//调用set方法进行赋值为"www.csdn.com"
else if(propClass=boolean.class||propClass=Boolean.class)//如果是boolean或Boolean都赋值为true
readMethod.invoke(javaBean,true)
else if(propClass==int.class||propClass==Integer.class)
readMethod.invoke(javaBean,100);
else if(propClass==double.class||propClass=Double.class)
readMethod.invoke(javaBean,0.01D);
}