内省: 一个变态的反射.
内省主要解决 的问题: 把对象的属性数据封装 到对象中。
属性描述器
构造方法:
public PropertyDescriptor(String propertyName,Class<?> beanClass)
propertyName:属性名称 beanClass:需要被设置属性的类的Class对象
方法:
public Method getWriteMethod() 获取属性的set方法。
public Method getReadMethod() 获取属性的get方法
内省类
Introspector
public static BeanInfo getBeanInfo(Class<?> beanClass)
BeanInfo
PropertyDescriptor[] getPropertyDescriptors()
package cn.itcast.introspector;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.junit.Test;
public class Demo2 {
@Test
public void getAllProperty() throws IntrospectionException{
BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor p : descriptors){
System.out.println(p.getReadMethod());
}
}
@Test
public void testProperty() throws Exception{
Person p = new Person();
PropertyDescriptor descriptor = new PropertyDescriptor("id", Person.class);
Method m = descriptor.getWriteMethod();
m.invoke(p,110);
Method readMethod = descriptor.getReadMethod();
System.out.println(readMethod.invoke(p, null));
}
}
BeanUtils
BeanUtils:
BeanUtils主要解决 的问题: 把对象的属性数据封装 到对象中。
BeanUtils的好处:
1. BeanUtils设置属性值的时候,如果属性是基本数据 类型,BeanUtils会自动帮我转换数据类型。
2. BeanUtils设置属性值的时候底层也是依赖于get或者Set方法设置以及获取属性值的。
3. BeanUtils设置属性值,如果设置的属性是其他的引用 类型数据,那么这时候必须要注册一个类型转换器。
BeanUtilss使用的步骤:
1. 导包commons-logging.jar 、 commons-beanutils-1.8.0.jar
package cn.itcast.introspector;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.crypto.Data;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
public class Demo3 {
public static void main(String[] args) throws Exception {
String id ="110";
String name="陈其";
String salary = "1000.0";
String birthday = "2013-12-10";
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) {
Date date = null;
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
date = dateFormat.parse((String)value);
}catch(Exception e){
e.printStackTrace();
}
return date;
}
}, Date.class);
Emp e = new Emp();
BeanUtils.setProperty(e, "id", id);
BeanUtils.setProperty(e, "name",name);
BeanUtils.setProperty(e, "salary",salary);
BeanUtils.setProperty(e, "birthday",birthday);
System.out.println(e);
}
}