基于JDK实现的动态代理demo

基于JDK实现的动态代理demo
1 package com.pojo;
2 
3 public interface Animal {
4     String eat(String foodName);
5     int sleep(int time);
6 }
Animal接口 基于JDK实现的动态代理demo
 1 package com.pojo.impl;
 2 
 3 import com.pojo.Animal;
 4 
 5 public class Pig implements Animal {
 6 
 7     @Override
 8     public String eat(String foodName) {
 9         System.out.println("吃了"+foodName);
10         return foodName;
11     }
12 
13     @Override
14     public int sleep(int time) {
15         System.out.println("睡了"+time);
16         return time;
17     }
18 }
实现Animal接口的Pig类 基于JDK实现的动态代理demo
package com.pojo.impl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;


public class ProxyPig implements InvocationHandler {

    private Object obj;
    public ProxyPig(Object obj){
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //方法之前做一个处理
        System.out.println("方法之前执行......\t"+method.getName()+"\t"+Arrays.toString(args));

        //被增强的方法
        Object value = method.invoke(obj,args);

        //方法之后执行
        System.out.println("方法之后执行\t"+value);

        return value;
    }
}
实现InvocationHandler接口的类 基于JDK实现的动态代理demo
package testMain;

import com.pojo.Animal;
import com.pojo.impl.Pig;
import com.pojo.impl.ProxyPig;
import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {
        Class[] c = {Animal.class};

        Animal pigAnimal = (Animal) Proxy.newProxyInstance(Pig.class.getClassLoader(), c, new ProxyPig(new Pig()));

        pigAnimal.eat("包子");
        pigAnimal.sleep(1000);
    }
}
主方法内进行测试

 

上一篇:java 泛型机制


下一篇:flutter isolate demo