java反射
-
Class.forName("java.lang.System")
Method[] m=c.getDeclareMethods();方法列表
Constructor构造
Modifier修饰符 Field字段
java动态代理
案例
定义接口和实现类
public interface Hello {
....public void say();
}
public class HelloWorld implements Hello{
....public void say() {
........System.out.println("hello world");
....}
}
public class HelloChina implements Hello {
....public void say() {
........System.out.println("hello china");
....}
}
动态代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class HelloHandler implements InvocationHandler {
....private Object proxyed;
....
....// 被代理的对象
....public HelloHandler(Object o)
....{
........this.proxyed = o;
....}
....
....public Object invoke(Object arg0, Method arg1, Object[] arg2)
............throws Throwable {
........Object result;
........// 方法调用之前
........System.out.println("start to say");
........// 反射invoke出方法列表,调用原始对象的方法
........result=arg1.invoke(this.proxyed, arg2);
........System.out.println("end say");
........return result;
....}
}
具体的使用
Hello hw =new HelloWorld();
// 代理调用world
InvocationHandler hander1=new HelloHandler(hw);
Hello proxy1=(Hello)Proxy.newProxyInstance(hw.getClass().getClassLoader(), hw.getClass().getInterfaces(), hander1);
proxy1.say();
// 代理调用china
Hello hc =new HelloChina();
InvocationHandler hander2=new HelloHandler(hc);
Hello proxy2=(Hello)Proxy.newProxyInstance(hc.getClass().getClassLoader(),hc.getClass().getInterfaces(), hander2);
proxy2.say();