黑马程序员内省JavaBean

------------- java培训、android培训、java博客、java学习型技术博客、期待与您交流! --------------

JavaBean简单来说是具有setter和getter方法的特殊类,该类将属性隐藏,并对外提供setter和getter方法。

示例:

packagecn.itcast.day1;

 

importjava.util.Date;

 

public class ReflectPoint {

    private Date birthday=new Date();

    private int x;

    public int y;

    public Date getBirthday() {

        return birthday;

    }

    public void setBirthday(Date birthday) {

        this.birthday = birthday;

    }

    public String str1="ball";

    public String str2="basketball";

    public String str3="itcast";

    public ReflectPoint(int x, int y) {

        super();

        this.x = x;

        this.y = y;

    }

    @Override

    public String toString(){

        return str1+":"+str2+":"+str3;

    }

    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;

    }

   

}

2、package cn.itcast.day1;

mportjava.beans.IntrospectionException;

importjava.beans.PropertyDescriptor;

importjava.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

 

importorg.apache.commons.beanutils.BeanUtils;

import org.apache.commons.beanutils.PropertyUtils;

 

public class IntroSpectorTest {

       publicstatic void main(String[] args) throws Exception{

              ReflectPointpt1=new ReflectPoint(3,5);

             

              //实用方法1,调用BeanUtils提供的工具,需要导入BeanUtils.jar包

              System.out.println(BeanUtils.getProperty(pt1,"x").getClass().getName());

              BeanUtils.setProperty(pt1,"x", "9");

              System.out.println(pt1.getX());

 

BeanUtils.setProperty(pt1, "birthday.time","11");

              System.out.println(BeanUtils.getProperty(pt1,"birthday.time"));

             

              //实用方法2:PropertyUtils,也需要导入PropertyUtils.jar包

PropertyUtils.setProperty(pt1,"x", 9);//PropertyUtils与BeanUtils有所不同,参数与源参数保持一致

              System.out.println(PropertyUtils.getProperty(pt1,"x").getClass());

             

       }

原文地址:https://www.cnblogs.com/kuyuyingzi/p/4266442.html