1. 程式人生 > >java反射修改private值和呼叫private函式

java反射修改private值和呼叫private函式

public class Test {
	public static void main(String[] args) {
		try {
			Field field = Student.class.getDeclaredField("name");
			Student student = new Student();
			field.setAccessible(true);
			field.set(student, "jack");
			student.getName();
			System.out.println(student.getName());
			
			Method method = Student.class.getDeclaredMethod("setTall", int.class);
			method.setAccessible(true);
			method.invoke(student, 178);
			System.out.println(student.getTall());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

可以看到其實使用發射可以直接操作private欄位和方法,其實會破壞封裝。