package com.nemo.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class User {
public String name;
public String passwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public static void testFields() throws Exception{
Class cls = Class.forName("com.nemo.reflect.User");
Object ob = cls.newInstance();
//获取所有字段
Field[] fields = cls.getDeclaredFields();
for(Field field:fields){
String fieldName = field.getName();
//根据方法名和形式参数获取method,new Class[]{}是形参数组
Method method = cls.getDeclaredMethod("set"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1), new Class[] { String.class });
//请求调用method
method.invoke(ob, new String[]{"love"});
}
//获取所有方法
Method[] methods = cls.getMethods();
for(Method method:methods){
//执行get方法
if(method.getName().startsWith("get")){
System.out.println(method.getName()+"的值是:"+method.invoke(ob, null));
}
}
}
public static void main(String[] args) throws Exception {
User.testFields();
}
}
执行结果:
getName的值是:love
getPasswd的值是:love
getClass的值是:class com.nemo.reflect.User