java反射机制经典实例

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



public class Test {

private static String message;

public static String getMessage() {
return message;
}
public Test(){

}
public static void setMessage(String message) {
Test.message = message;
}

public static String printStr(String str){
return str + "," + message;
}

public static void main(String[] args) throws Exception {

Class<Test> t = Test.class;//利用反射原理 获取Test类
Object obj = t.newInstance();//实例化一个Test
Field f = t.getDeclaredField("message");//获取message属性
f.set(t, "hello world!");//设置message属性
Method m = t.getMethod("printStr", new Class[]{String.class});//获取printStr方法
String result = (String) m.invoke(obj, new Object[]{"zhangsan"});//执行printStr方法
System.out.println(result);


}


}

你可能感兴趣的:(java反射机制)