package com.alex.ssh.tool;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 用Java反射機制來調用private方法
* @author WalkingDog
*
*/
public class Reflect {
public static void main(String[] args) throws Exception {
//直接創建對象
Person person = new Person();
Class<?> personType = person.getClass();
//訪問私有方法
//getDeclaredMethod可以獲取到所有方法,而getMethod只能獲取public
Method method = personType.getDeclaredMethod("say", String.class);
//壓制Java對訪問修飾符的檢查
method.setAccessible(true);
//調用方法;person為所在對象
method.invoke(person, "Hello World !");
//訪問私有屬性
Field field = personType.getDeclaredField("name");
field.setAccessible(true);
//為屬性設置值;person為所在對象
field.set(person, "WalkingDog");
System.out.println("The Value Of The Field is : " + person.getName());
}
}
//JavaBean
class Person{
private String name;
//每個JavaBean都應該實現無參構造方法
public Person() {}
public String getName() {
return name;
}
private void say(String message){
System.out.println("You want to say : " + message);
}
}