java实现 * 示例分享
时间:2023-04-28 15:54:49
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class LogHandler implements InvocationHandler {
private Object delegate;
public Object bind(Object delegate) {
this.delegate = delegate;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
delegate.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
System.out.println("方法开始:" + method);
result = method.invoke(delegate, args);
System.out.println("方法结束:" + method);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
public interface Animal {
public void hello();
}
* 作为代理模式的一种扩展形式,广泛应用于框架(尤其是基于AOP的框架)的设计与开发,本文将通过实例来讲解Java * 的实现过程。
public class Monkey implements Animal {
@Override
public void hello() {
// TODO Auto-generated method stub
System.out.println("hello");
}
}
public class Main {
public static void main(String[] args) {
LogHandler logHandler = new LogHandler();
Animal animal = (Animal) logHandler.bind(new Monkey());
animal.hello();
}
}