一、项目中使用了 Introspector 。以下是我学习 Introspector 的代码
public class MyBean extends TestIntrospector{
private String id = null;
private String usreName = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsreName() {
return usreName;
}
public void setUsreName(String usreName) {
this.usreName = usreName;
}
}
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class TestIntrospector {
private MyBean beanObj = null;
private BeanInfo bBeanObjInfo = null;
private String output = "";
private String methodParams = new String();
public void testIntrospector(){
try
{
//实例化一个Bean
beanObj = new MyBean();
//依据Bean产生一个相关的BeanInfo类
bBeanObjInfo = Introspector.getBeanInfo(beanObj.getClass());
output = "内省成员方法:\n";
/* BeanInfo.getMethodDescriptors() 用于获取该Bean中的所有允许公开的成员方法,以MethodDescriptor数组的形式返回 */
/* MethodDescriptor类 用于记载一个成员方法的所有信息 */
MethodDescriptor[] mehtodDesc = bBeanObjInfo.getMethodDescriptors();
for (int i = 0; i < mehtodDesc.length; i++) {
/* MethodDescriptor.getName()获得该方法的方法名字 */
String methodName = mehtodDesc[i].getName();
/* MethodDescriptor.getMethod() 获得该方法的方法对象(Method类)*/
/* Method类 记载一个具体的的方法的所有信息 */
Method methodObj = mehtodDesc[i].getMethod();
/* Method.getParameterTypes() 获得该方法所用到的所有参数类型,以Class数组的形式返回 */
Class[] parameters = methodObj.getParameterTypes();
if(parameters.length > 0){
for (int j = 0; j < parameters.length; j++) {
methodParams = parameters[j].getName();
}
}
output += methodName + "(" + methodParams + ")\n";
}
System.out.println(output);
System.out.println("------------------------------------------\n");
output = "内省成员属性\n";
/* bBeanObjInfo.getPropertyDescriptors(),用于获取该Bean中的所有允许公开的成员属性,以PropertyDescriptor数组的形式返回 */
/* PropertyDescriptor类 用于描述一个成员属性 */
PropertyDescriptor[] propertyDesc = bBeanObjInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDesc.length; i++) {
/* PropertyDescriptor.getName() 获得该属性的名字 */
String propertyName = propertyDesc[i].getName();
Class propertyType = propertyDesc[i].getPropertyType();
output += propertyName + " ( " + propertyType.getName() + " )\n";
}
System.out.println(output);
}catch(IntrospectionException e){
System.out.println("Java Bean 内省发生异常。");
e.printStackTrace();
}
}
public static void main(String[] arg){
new TestIntrospector().testIntrospector();
}
}