java 动态代理的使用
程序员文章站
2022-03-24 23:31:04
...
1.接口Human.java
public interface Human { void say(); }
2.Human的实现类 Person
public class Person implements Human { @Override public void say() { System.out.println("haha"); } }
3.处理类
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class Hander implements InvocationHandler { private Object obj; public Hander(Object obj) { this.obj = obj; } public Hander() { } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); method.invoke(obj, args); System.out.println("after"); return null; } }
4. 使用
import java.lang.reflect.Proxy; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Human i = (Human) Proxy.newProxyInstance(Thread.currentThread() .getContextClassLoader(), Person.class.getInterfaces(), new Hander(new Person())); i.say(); } }
5. 输出结果
before haha after
下一篇: 记一次oracle数据库恢复