这是黑马的一道入学测试题,代码如下:
/**
* 要求:
存在一个JavaBean,已知字符串形式的类名,并且它包含以下几种可能的属性:
1:boolean/Boolean 2:int/Integer 3:String 4:double/Double
属性名未知(这句话是重点!!!),现在要给这些属性设置默认值(题目的本质:根据属性类型,设置属性值!!),以下是要求的默认值:
String类型的默认值为 字符串
int/Integer类型的默认值为100
boolean/Boolean类型的默认值为true
double/Double的默认值为0.01D.
只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现.
* 思路:
* 1.获取BeanDescriptor数组,遍历之
* 2.获取readMethod、获取writeMethod、获取name、获取类型
* 3.根据参数类型进行赋值
* 4.打印调试信息
* @author yajun
*/
public class Bean5 {
private void initialise(){
@SuppressWarnings("rawtypes")
Class beanClass;
BeanInfo beanInfo;
PropertyDescriptor[] pds;
Type type;
Method readMethod;
Method writeMethod;
Object obj;
String name;
try {
beanClass = Class.forName("javabean.TempBean");
obj=beanClass.newInstance();
beanInfo=Introspector.getBeanInfo(beanClass);
pds=beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd:pds){
/**
* 1.获取readMethod,获取writeMethod,获取Type
* (获取Method的参数类型,不必这么麻烦,直接有getPropertyType方法)
* 2.如果writeMethod不为空,根据参数类型赋初值
*/
type=pd.getPropertyType();
readMethod=pd.getReadMethod();
writeMethod=pd.getWriteMethod();
name=pd.getName();
//所有的类都继承Object类,Object类有一个getClass方法,需要排除。
if("class".equals(name)){
continue;
}
if(writeMethod!=null){
if(type==int.class||type==Integer.class){
writeMethod.invoke(obj, 100);
}
if(type==String.class){
writeMethod.invoke(obj, "字符串");
}
if(type==boolean.class||type==Boolean.class){
writeMethod.invoke(obj, true);
}
if(type==double.class||type==Double.class){
writeMethod.invoke(obj, 0.01D);
}
}
//调试信息
if(readMethod!=null){
System.out.println(readMethod.invoke(obj));
}
}//End of for
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
@Test
public void testInitialize(){
initialise();
}
}
/**
* 测试用的bean
* @author yajun
*/
class TempBean{
private String name;
private int id;
private boolean sex;
private double score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}