## 動態代理實現
> `JDK代理`
實現`InvocationHandler`接口并實現`invoke(Object proxy, Method method, Object[] args)`方法
ep:
~~~
public class StudentInvocation<T> implements InvocationHandler{
?
private T t;
public StudentInvocation(T t) {
this.t = t;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws ? ? ? ? Throwable {
System.out.println("-----方法執行前----");
System.out.println("方法名:"+method.getName());
Object result = method.invoke(t, args);
System.out.println("結果:"+ result);
System.out.println("-----方法執行后----");
return result;
}
?
? ?/**
* 創建代理類
* @return
*/
public T createProxy() {
return (T) Proxy.newProxyInstance(t.getClass().getClassLoader(),
t.getClass().getInterfaces(), this);
}
}
~~~
> `CJLB代理`
實現`MethodInterceptor`并實現方法`intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3)`方法
ep:
~~~
public class CglbProxy implements MethodInterceptor {
?
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
?System.out.println("cglb執行前");
// Object invokeSuper = arg3.invoke(arg0, arg2);
?Object invokeSuper = arg3.invokeSuper(arg0, arg2);
?System.out.println("cglb執行后");
?return invokeSuper;
}
/**
* 創建代理類
* @param clazz
* @return
*/
public Object createProxy(Class clazz) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}
?
}
~~~
**tip:注解的實現**
注解的實現也是用了代理類,其中會將在注解中設置的屬性放入其實現代理類的`memberValues`字段中。
- 2111總結
- 1.面向對象
- 1.0.1 super()與this()的區別
- 1.0.2 private、default、protected、public的訪問范圍
- 1.0.3 continue、break、return區別
- 1.0.4 重載和重寫的區別
- 1.0.5 final的特點
- 1.0.6 抽象類與接口的區別
- 1.0.7 java類型
- 1.0.8 什么是反射
- 1.0.9 類的加載機制
- 1.1.1 jvm內存結構
- 1.1.2 java垃圾回收機制
- 1.1.3 并發問題
- 1.1.3.1 線程的狀態與關系
- 1.1.3.2 并發的三大性質
- 1.1.3.3 線程的實現與使用
- 1.1.3.4 線程池相關
- 1.1.3.5 并發相關方法
- 1.1.3.6 線程相關工具
- 1.1.4 jdk8特性
- 1.1.4.1 lambad表達式的使用
- 1.1.4.2 stream API
- 1.1.4.3 Optional容器使用
- 1.1.4.4 LocalDateTime
- 1.15 io流
- 1.16 動態代理實現
- 2.JavaEE
- 2.0.1 JSP四大作用域九大內置對象
- 2.0.2 cookie與session的區別
- 4.數據庫相關
- 5.git版本管理
- 7.一些問題解決
- 7.1 分布式鎖如何實現