【java标准库系列】java反射与动态代理

直接上源码。

动态代理

package com.jxdw.reflect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Subject{
public String say(String name,int age);
}

class RealSubject implements Subject{
@Override
public String say(String name, int age) {
return name + " " + age;
}
}

class MyInvocationHandler implements InvocationHandler{
private Object object=null;
public Object bind(Object object){
this.object=object;
return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(this.object,args);
}
}
public class ProxyHello {
public static void main(String[] args) {
MyInvocationHandler myInvocationHandler=new MyInvocationHandler();
Subject realSubject=(Subject) myInvocationHandler.bind(new RealSubject());
System.out.println("info:"+realSubject.say("xiaogang",20)+"\n");
}
}