• 吴裕雄--天生自然JAVA反射机制学习笔记:动态代理


    class Person{};
    public class ClassLoaderDemo{
        public static void main(String args[]){
            Person stu = new Person() ;
            System.out.println("类加载器:" + stu.getClass().getClassLoader().getClass().getName()) ;
        }
    };
    import java.lang.reflect.InvocationHandler ;
    import java.lang.reflect.Proxy ;
    import java.lang.reflect.Method ;
    interface Subject{
        public String say(String name,int age) ;    // 定义抽象方法say
    }
    class RealSubject implements Subject{    // 实现接口
        public String say(String name,int age){
            return "姓名:" + name + ",年龄:" + age ;
        }
    };
    class MyInvocationHandler implements InvocationHandler{
        private Object obj ;
        public Object bind(Object obj){
            this.obj = obj ;    // 真实主题类
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this) ;
        }
        public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
            Object temp = method.invoke(this.obj,args) ;    // 调用方法
            return temp ;
        }
    };
    public class DynaProxyDemo{
        public static void main(String args[]){
            Subject sub = (Subject)new MyInvocationHandler().bind(new RealSubject()) ;
            String info = sub.say("李兴华",30) ;
            System.out.println(info) ;
        }
    };
  • 相关阅读:
    java中 == 与equals 的区别
    java中的多线程 // 基础
    MySQL-锁机制
    将博客搬至CSDN
    MySQL-事务
    MySQL-存储过程
    MySQL-触发器
    MySQL-视图
    Redis设置Auth认证保护
    PHP目前常见的五大运行模式
  • 原文地址:https://www.cnblogs.com/tszr/p/12416993.html
Copyright © 2020-2023  润新知