JAVA 通过反射获取公共和私有成员变量和成员方法(二)
JAVA通过反射创建对象可以查看以下介绍。 JAVA通过反射来创建对象(一)
类对象文件
package com.csdn;
public class Student {
private String name;
private int age;
public String height;
protected int num;
public Student() {
}
public void print1(){
System.out.println("public print1");
}
private void print2(){
System.out.println("private print2");
}
private void print3(int a){
System.out.println(a);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", height='" + height + '\'' +
", num=" + num +
'}';
}
}
1.通过反射获取类的所有的成员变量
package com.csdn;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class reflecttest {
public static void main(String[] args) throws ClassNotFoundException{
Class<?> c = Class.forName("com.csdn.Student");
Field[] fields = c.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println("--------------");
Field[] f2 = c.getDeclaredFields();
for (Field field : f2) {
System.out.println(field);
}
}
}
2.通过反射获取类的单个成员变量,并用反射给成员变量赋值
package com.csdn;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class reflecttest {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> c = Class.forName("com.csdn.Student");
Field height = c.getField("height");
Field pri_name = c.getDeclaredField("name");
Constructor<?> con = c.getConstructor();
Student s = (Student) con.newInstance();
pri_name.setAccessible(true);
height.set(s, "198cm");
pri_name.set(s, "张三");
System.out.println(s);
}
}
3.通过反射获取类的单个成员方法,并用调用。
package com.csdn;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class reflecttest {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> c = Class.forName("com.csdn.Student");
Method print1 = c.getDeclaredMethod("print1");
Method print2 = c.getDeclaredMethod("print2");
Method print3 = c.getDeclaredMethod("print3", int.class);
print2.setAccessible(true);
print3.setAccessible(true);
Constructor<?> constructor = c.getConstructor();
Object o = constructor.newInstance();
print1.invoke(o);
print2.invoke(o);
print3.invoke(o,3);
}
}
|