黑马程序员--反射

---------------------- android培训java培训、期待与您交流! ----------------------

内省(Introspector)   内省就是特殊的反射 反射一个类的属性
为什么要学内省?
开发框架时,经常需要使用java对象的属性来封装程序的数据,每次都使用反射技术完成此类操作过于麻烦,所以sun公司开发了一套API,专门用于操作java对象的属性。

什么是Java对象的属性和属性的读写方法?
属性就是方法名字为getXxx中xxx就是属性 属性就是javabean 一个标准的javabean必须有一个默认的构造函数,属性私有,提供get和set方法

内省访问JavaBean属性的两种方式:
通过PropertyDescriptor类操作Bean的属性
通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法

 

内省—beanutils工具包
Sun公司的内省API过于繁琐,所以Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils
Beanutils工具包的常用类:
BeanUtils
PropertyUtils
ConvertUtils.regsiter(Converter convert, Class clazz)
自定义转换器

 

public class Six {
  @Test
  public void reflect() throws Exception{
//   获取Class对象  有四种方法
// 第一种   类名.class   Class clazz=Student.class;
// 第二种    用类的对象获取   Student s=new Student();    Class clazz=s.getClass();
//  第三种   用Class类的静态方法    类名的字符串形式要用绝对路径    (第四种方法忘了 看视频)
//   Class clazz=Class.forName("cn.itcast.bin.day3.Student");
   Class clazz=Student.class;
//   获取所有的构造方法  (有Declared 能获取私有的)
   Constructor []c=clazz.getDeclaredConstructors();
//   遍历所有的构造函数
   for(Constructor cc:c){
    System.out.println(cc.toString());
   }
//   根据遍历所有构造函数得到的构造函数的参数类型获取指定的构造函数
  Constructor co= clazz.getDeclaredConstructor(null);//获取到无参的构造函数
  Constructor co1=clazz.getDeclaredConstructor(String.class);//获取到参数是string类型的构造函数
//  根据得到的构造函数可以创建对象 即newinstance
  Student sd= (Student) co.newInstance();//用co这个无参的构造函数创建对象
  System.out.println(sd.sex);
  Student sd1= (Student) co1.newInstance("哈哈");//用co1这个有参的构造函数创建对象
  System.out.println(sd1.sex);
  //获取所有的字段field
  Field [] f=clazz.getDeclaredFields();
//  遍历所有字段(包括所有private的)
  for(Field ff:f){
   ff.setAccessible(true);//访问私有的要设置访问权限为true 否则无法访问私有的
   System.out.println(ff.toString()+"......."+ff.get(sd));//用get(obeject)获取字段的值 需要传入一个该类对象
  }
//  获取所有方法(包括private的 要想获取私有的必须有Declared)
  Method [] m= clazz.getDeclaredMethods();
//  遍历所有方法
  for(Method mm:m){
   System.out.println(mm.toString());
  }
//  根据遍历得到的每一个方法的name, 参数类型具体得到每一个method
 Method m1= clazz.getDeclaredMethod("run", null);
 Method m2= clazz.getDeclaredMethod("show", int.class,String.class);
 Method m3=clazz.getDeclaredMethod("eat", String [].class,int [].class);
// 调用得到的方法 需要传入一个该类实例对象和具体参数 用invoke调用
 m1.invoke(sd, null);
 m2.setAccessible(true);//调用私有的方法要设置setaccessable访问权限为true
 m2.invoke(sd, 1,"哈哈");
 m3.invoke(sd, new String [1],new int [1]);
  }
}

//sun公司内省api操作bean的属性
public class Demo1 {

 @Test
 public void test1() throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
  
  Student bean = new Student();
  
  //得到bean的所有属性
  BeanInfo info = Introspector.getBeanInfo(Student.class);
  
  //得到bean的所有属性描述器
  PropertyDescriptor pds[] = info.getPropertyDescriptors();
  
  for(PropertyDescriptor pd : pds){  //name
   String propertyName = pd.getName();
   if(propertyName.equals("name")){
   //getWriteMethod();是获取set或get属性的方法
    Method  m = pd.getWriteMethod();  //setName(String name)
    m.invoke(bean, "flx");
   }
  }
  System.out.println(bean.getName());
 }
 
 //操作bean的指定属性: age
 @Test
 public void test2() throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
  
  Student bean = new Student();
  //获取指定的属性描述器
  PropertyDescriptor pd = new PropertyDescriptor("age",bean.getClass());
  Method method = pd.getWriteMethod();  //setAge(int age)
  method.invoke(bean, 12);
  
  //通过内省获取bean的age属性
  method = pd.getReadMethod(); //  getAge()
  int age = (Integer) method.invoke(bean, null);
  System.out.println(age);
  
 }
 
}

//使用beanuitls框架操作bean的属性
public class Demo1 {

 
 //基本操作
 @Test
 public void test1() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
  Student bean = new Student();
  BeanUtils.setProperty(bean, "name", "flx");
  String name = BeanUtils.getProperty(bean, "name");
  System.out.println(name);
 }
 
 //较高级的操作
 @Test
 public void test2() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
  Student bean = new Student();
  BeanUtils.setProperty(bean, "age", "12");  //beanutils框架会自动对数据进行转换,这仅于8种基本数据类型
  System.out.println(bean.getAge()+1);
 }
 
 //高级的操作
 @Test
 public void test3() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
  Student bean = new Student();
  
  //注册日期转换器
  ConvertUtils.register(new Converter(){
   public Object convert(Class type, Object value) {
    if(value==null){
     return null;
    }
    if(!(value instanceof String)){
     throw new ConversionException("只支持字符串的转换");
    }
    String date = (String) value;
    if(date.trim().equals("")){
     return null;
    }
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {
     return df.parse(date);
    } catch (ParseException e) {
     throw new ConversionException(e);
    }
   }
  }, Date.class);
  
  BeanUtils.setProperty(bean, "birthday", "");  //beanutils框架会自动对数据进行转换
  System.out.println(bean.getBirthday());  //date.toString()
 }
 
 
 //高级的操作
 @Test
 public void test4() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
  Student bean = new Student();
  
  //使用beanutils框架内置的转换器
  ConvertUtils.register(new DateLocaleConverter(), Date.class);
  BeanUtils.setProperty(bean, "birthday", "");  //beanutils框架会自动对数据进行转换
  System.out.println(bean.getBirthday());  //date.toString()
 }
 
}

 

 

---------------------- android培训java培训、期待与您交流! ----------------------详细请查看: http://edu.csdn.net/heima
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值