Java利用反射操作成员变量,方法

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Test1 {


private String name;

private int  age;

private String sex;


public String getName() {
return name;
}


public Test1() {
super();
}


public Test1(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}


public void setName(String name) {
this.name = name;
}


public int getAge() {
return age;
}


public void setAge(int age) {
this.age = age;
}


public String getSex() {
return sex;
}


public void setSex(String sex) {
this.sex = sex;
}


@Override
public String toString() {
return "Test1 [name=" + name + ", age=" + age + ", sex=" + sex + "]";



}






import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;


public class Test2fanshe {


public static void main(String[] args) throws Exception {
Object object = Class.forName("Test1").newInstance();
System.out.println("className:" + object.getClass());
Class cls = object.getClass();
// 获取成员变量
Field[] declaredFields = cls.getDeclaredFields();
System.out.println("declaredFields.length:" + declaredFields.length);
for (Field x : declaredFields) {
System.out.println("FieldsName:" + x.getName());
System.out.println("FieldsType:" + x.getType());
}
System.out.println("--------------------------------------------------------------------------");
// 获得成员方法列表
Method[] declaredMethods = cls.getDeclaredMethods();
System.out.println("declaredMethods.length:" + declaredMethods.length);
for (Method x : declaredMethods) {
System.out.println("MethodName:" + x.getName());
System.out.println("ReturnType:" + x.getReturnType());
Parameter[] parameters = x.getParameters();
for (Parameter x1 : parameters) {
System.out.println("ParameterName:" + x1.getName());
System.out.println("ParameterType:" + x1.getType());
System.out.println("=============================================");
}
if (x.getName().equals("setName")) {
x.invoke(object, "王晨");
}
if (x.getName().equals("setAge")) {
x.invoke(object, 11);
}
if (x.getName().equals("setSex")) {
x.invoke(object, "人妖");
}
System.out.println(object);
}


}


}

你可能感兴趣的:(Java利用反射操作成员变量,方法)