接口 BCInterface
public interface BCInterface {
void enhancement();
}
实现类 BCEnhancement.java
public class BCEnhancement implements BCInterface{
public void enhancement() {
System.out.println("hello enhancement");
}
}
LogProxy.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class LogProxy implements InvocationHandler {
private Object object;
public Object getProxyObject(Object o){
object=o;
try{
return Proxy.newProxyInstance(this.getClass().getClassLoader(),o.getClass().getInterfaces(),this);
}catch (IllegalArgumentException e){
throw new RuntimeException(e);
}
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before invoke ...");
Object result= method.invoke(object,args);
System.out.println("after invoke ...");
return result;
}
}
测试类 Test.java
public class Test {
public static void main(String[] args) {
LogProxy logProxy = new LogProxy();
System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
BCInterface byteCodeEn = (BCInterface) logProxy.getProxyObject(new BCEnhancement());
byteCodeEn.enhancement();
}
}
输出:
before invoke ... hello enhancement after invoke ...
原文:https://www.cnblogs.com/loytime/p/11749979.html