利用反射获取类的私有属性和私有方法

一般来说,对于Student类的私有属性和方法,别的类不能够访问。但利用反射,则可以访问

Test类:

package fanshe;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {

	public static void main(String[] args) {
		try {
			Student student = Student.class.newInstance();
			Field[] fields = Student.class.getDeclaredFields();
			System.out.println("Student类的所以属性名称为:");
			for (Field field : fields) {
				field.setAccessible(true);
				System.out.println(field.getName());
			}
			
			Field field = Student.class.getDeclaredField("name");
			field.setAccessible(true);
			Object name = field.get(student);
			System.out.println("修改之前的name:"+name);
			field.set(student, "ymy");
			name = field.get(student);
			System.out.println("修改之后的name:"+name);
			
			Method method = Student.class.getDeclaredMethod("study", String.class);
			method.setAccessible(true);
			method.invoke(student, name);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}

Student类:

package fanshe;

public class Student {

	private int id=111;
	private int age=10;
	private String name="gong";
	
	private void study(String name) {
		System.out.println(name+" is studying....");
	}
}

最后的运行结果:

猜你喜欢

转载自blog.csdn.net/JackGong1999/article/details/88067220