Java反射
Student文件
package reflex;
public class Student {
private String name;
private int age;
private String sex;
private int height;
private int weight;
public Student(String name, int age, String sex, int height, int weight) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.height = height;
this.weight = weight;
}
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
int currentAge = 0;
if (currentAge == 10)
System.out.println("实现");
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
访问成员变量文件
package reflex;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Hello {
public static void main(String[] args) {
try {
Class<?> class1 = Class.forName("reflex.Student");
System.out.println((Student)class1.newInstance());
Method[] list = class1.getDeclaredMethods();
for(Method method:list) {
System.out.println("获取方法名"+method.getName());
System.out.println("获取返回函数类型"+method.getReturnType());
System.out.println("获取传入参数类型"+method.getParameterTypes());
}
Object newInstance = class1.newInstance();
Field f = class1.getDeclaredField("name");
Field f1 = class1.getDeclaredField("age");
f1.setAccessible(true);
f.setAccessible(true);
f.set(newInstance, "zhangsan");
f1.set(newInstance, 12);
Student student = (Student) newInstance;
Method method = class1.getMethod("setAge", int.class);
method.invoke(newInstance, (Object)10);
System.out.println(student.getName());
System.out.println(student.getAge());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}