public class TestUser {
public static void main(String args [] ) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Class bean = null;
try {
bean = Class.forName("inject.User");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("can't find class");
e.printStackTrace();
}
BeanInfo info = null;
try {
info = Introspector.getBeanInfo(bean);
} catch (IntrospectionException e) {
// TODO Auto-generated catch block
System.out.println("get the information of the class");
e.printStackTrace();
}
// 遍历指定类的方法
MethodDescriptor[] methods = info.getMethodDescriptors();
for (int i = 0; i < methods.length; i++) {
System.out.println("方法:"+methods[i].getDisplayName());
}
// 遍历指定类的属性
PropertyDescriptor[] propertys = info.getPropertyDescriptors();
for (int j = 0; j < propertys.length; j++) {
System.out.println("属性:"+propertys[j].getName());
}
Object obj = bean.newInstance();
Method mSet = null;
for(int k = 0; k < propertys.length; k++){
mSet = propertys[k].getWriteMethod();
if(propertys[k].getName().equalsIgnoreCase("name")){
mSet.invoke(obj, "mutou");
continue;
}
if(propertys[k].getName().equalsIgnoreCase("password")){
mSet.invoke(obj, "mutou_password");
continue;
}
}
User user = (User)obj;
System.out.println(user.getName());
System.out.println(user.getPassword());
}
}
<pre name="code" class="java">public class User {
String name;
String password;
//setter getter no paragram constructor
}
输出
方法:notify
方法:wait
方法:setPassword
方法:getClass
方法:getName
属性:class
属性:name
属性:password
mutou
mutou_password
参考资料 http://blog.csdn.net/zhikun518/article/details/7185499