就我目前看的资料有两种实现手段:
1)利用java.lang.reflect.*中的类和接口,相信大家都很熟啦!
2)主要是利用java.beans.*中的BeanInfo接口和Introsepector类,Demo如下:
操作的JAVABEAN:
package me.jdk.reflect;
public class JavaBean {
private String name;
private String password;
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}
/**
* @param password The password to set.
*/
public void setPassword(String password) {
this.password = password;
}
/**
*
*/
public JavaBean() {
// TODO Auto-generated constructor stub
}
}
实现内现的类:
/**
*
*/
package me.jdk.reflect;
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.util.Enumeration;
/**
* 功能描述:实现Introsepector
* @create on: 2006-12-15
*/
public class MyReflect<E> {
/**
*
*/
public MyReflect() {
// TODO Auto-generated constructor stub
}
public void testReflect(Class cls) {
BeanInfo info = null;
try {
info = Introspector.getBeanInfo(cls,Object.class);
PropertyDescriptor[] properties = info.getPropertyDescriptors();
for(int i = 0; i < properties.length; i++ )
System.out.println("properties["+i+"].getName()"+properties[i].getName());
MethodDescriptor[] methods = info.getMethodDescriptors();
for(int j = 0; j < methods.length; j++)
System.out.println("methods["+j+"].getName()"+methods[j].getName());
}
} catch (IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
*@return_type void
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyReflect reflect = new MyReflect();
reflect.testReflect(me.jdk.reflect.JavaBean.class);
}
}