反射就是把java类中的各种成分映射成为相应的java类。
例如:一个java类用一个Class类的对象来表示,一个类中的组成部分:成员变量、方法、构造函数、包等等信息,也用一个个java类来表示,获得其中的变量,方法,构造函数,修饰符,包等信息,这些信息就是用相应类的实例对象来表示,它们是Field、Method、Constructor、Package等等
String name="com.test.Person";
Class c=Class.forName(name);
//或者Class c=obj.getClass;
Method m[]=c.getDeclaredMethods();
反射技术实际已经能够完全满足我们对javabean的各种操作了,但是为了方便jdk还是为我们提供了一套操纵javabean的api,称之为
内省操作(Introspector)
内省是 Java 语言对 Bean 类属性、事件的一种缺省处理方法。例如类 A 中有属性 name, 那我们可以通过 getName,setName 来得到其值或者设置新的值。通过 getName/setName 来访问 name 属性,这就是默认的规则。 Java 中提供了一套 API 用来访问某个属性的 getter/setter 方法,通过这些 API 可以使你不需要了解这个规则(但你最好还是要搞清楚),这些 API 存放于包 java.beans 中。
一般的做法是通过类 Introspector 来获取某个对象的 BeanInfo 信息,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的getter/setter 方法,然后我们就可以通过反射机制来调用这些方法。
下面示范两种内省操作,首先给一个javabean
public class UserBean {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第一种方法较为繁琐,但通常在批量操作javabean时很管用
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;
public class UserBeanHandlerOne {
public static void main(String args[]) {
UserBean user = new UserBean();
try {
handleBean(user);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void handleBean(UserBean user)
throws IntrospectionException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
BeanInfo bi = Introspector.getBeanInfo(user.getClass());
PropertyDescriptor[] pd = bi.getPropertyDescriptors();
for (PropertyDescriptor p : pd) {
String attrName=p.getName();
if(attrName.equals("name")||attrName.equals("age")){
Method writeMethod=p.getWriteMethod();//得到set方法
Class clazz[]=writeMethod.getParameterTypes();
if(clazz[0]==int.class)
writeMethod.invoke(user, 20);
else
writeMethod.invoke(user, "peter");//执行set方法
Method readMethod = p.getReadMethod();//获取get方法
Object obj = readMethod.invoke(user);//执行get方法
System.out.println(obj);
}
}
}
}
第二种方法是对于某个特定的属性
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class UserBeanHandlerTwo {
public static void main(String args[]) throws IntrospectionException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException{
UserBean ub=new UserBean();
PropertyDescriptor pd=new PropertyDescriptor("name",UserBean.class);
Method writeMethod=pd.getWriteMethod();
writeMethod.invoke(ub,"peter");
Method readMethod=pd.getReadMethod();
Object str=readMethod.invoke(ub);
System.out.println(str);
}
}