1. 程式人生 > >很簡單Java動態代理實現

很簡單Java動態代理實現

targe ace custom err ble java動態代理 cat pro sep

1.Base接口

public interface Base {
    void baseMethod();
}

2.CustomHandler類

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

public class CustomHandler<T> implements InvocationHandler {
    T target;

    public CustomHandler(T target){
        this
.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("start..."); Object result = method.invoke(target, args); System.out.println("end..."); return result; } }

3.測試

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class ProxyTest {

    public static void main(String[] args) {
        Base base = () -> System.out.println("in hand...");
        InvocationHandler handler = new CustomHandler<>(base);
     // 生成代理對象 Base baseProxy
= (Base)Proxy.newProxyInstance(ProxyTest.class.getClassLoader(), new Class[]{Base.class}, handler); baseProxy.baseMethod(); } }
start...
in hand...
end...

Process finished with exit code 0

很簡單Java動態代理實現