- package cyc.dl;
- public interface Subject { //定义接口
- public String say(String name,int age ) ;
- }
- package cyc.dl;
- public class RealSubject implements Subject { //实现接口
- public String say(String name,int age){
- return "姓名:" + name + "年龄:" + age ;
- }
- }
- package cyc.dl;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- public class MyInvocationHandler implements InvocationHandler{ //代理类
- private Object obj; //定义一个真实主体
- public Object bind(Object obj){ //用一个方法绑定真实操作主体
- this.obj = obj ;
- return Proxy.newProxyInstance(obj.getClass().getClassLoader(), //类加载器 此语句什么作用,参数,this是啥
- obj.getClass().getInterfaces(), this); //取得代理对象
- }
- public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
- Object temp = method.invoke(this.obj, args) ;
- return temp ;
- }
- }
- package cyc.dl;
- public class DynaProxyDemo { //测试类
- public static void main(String args[]){
- MyInvocationHandler handler = new MyInvocationHandler() ;
- Subject sub = (Subject)handler.bind(new RealSubject()) ;
- String info = sub.say("阿菜", 21) ;
- System.out.println(info);
- }
- }
复制代码
代码虽然出来了,但是有些地方看不懂,帮忙解释一下??
|
|