- package com.itheima;
- import java.beans.BeanInfo;
- import java.beans.IntrospectionException;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- /**
- * 存在一个JavaBean,它包含以下几种可能的属性: 1:boolean/Boolean 2:int/Integer 3:String
- * 4:double/Double 属性名未知,现在要给这些属性设置默认值,以下是要求的默认值: String类型的默认值为字符串
- * www.itheima.com int/Integer类型的默认值为100 boolean/Boolean类型的默认值为true
- * double/Double的默认值为0.01D.
- * 只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现
- * @author Liu wangfang
- */
- public class Test_5 {
- public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- //1.创建一个javaBean对象;
- JavaBean jb = new JavaBean();
- //2.使用內省中方法获得BeanInfo对象;
- BeanInfo bi = Introspector.getBeanInfo(jb.getClass());
- //3.获得BeanInfo中的属性描述器数组;
- PropertyDescriptor[] pds = bi.getPropertyDescriptors();
- //4.遍历数组,判断属性的类型是否是要求的类型,如果是,就设置默认值;
- for(PropertyDescriptor pd : pds){
- //5.遍历每个属性描述器时,先获得其set方法;
- Method method = pd.getWriteMethod();
- //6.判断属性的类型是否是题目要求的类型
- if(pd.getPropertyType()==boolean.class ||pd.getPropertyType()==Boolean.class){
- //7.set方法的调用,赋值
- method.invoke(jb,true);
- } if(pd.getPropertyType()==int.class ||pd.getPropertyType()==Integer.class){
- method.invoke(jb,100);
- } if(pd.getPropertyType()==double.class ||pd.getPropertyType()==Double.class){
- method.invoke(jb,0.01D);
- } if(pd.getPropertyType()==String.class ){
- method.invoke(jb,"www.itheima.com");
- }
- }
- // System.out.println(jb);
- }
- }
- class JavaBean{
- private boolean flag;
- private int num;
- private String name;
- private double db;
- private char c;
- public boolean isFlag() {
- return flag;
- }
- public void setFlag(boolean flag) {
- this.flag = flag;
- }
- public int getNum() {
- return num;
- }
- public void setNum(int num) {
- this.num = num;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public double getDb() {
- return db;
- }
- public void setDb(double db) {
- this.db = db;
- }
- // public String toString(){
- // return name +"**"+ db + "**"+num +"**"+ flag;
- // }
- }
复制代码 这是之前考试做的一道题,你可以参考一下 |