圖片.png
圖片.png
自定義注解
開發(fā)步驟
- 創(chuàng)建一個@interface
- String value();抽象方法用以接收數(shù)據(jù)
- 使用元注解,描述自定義注解
- @Target指定注解可以加在哪里
- ElementType.TYPE:可在類和接口上面
- ElementType.METHOD:可方法上
- ElementType.FIELD:可在屬性
- @Retention指定注解在什么時候有用
- RetentionPolicy.RUNTIME:注解保留到運(yùn)行時
- RetentionPolicy.ClASS:注解保留到Class文件中
- RetentionPolicy.SOURCE:注解保留到j(luò)ava編譯時期
- @Inherited可以被繼承
jdk動態(tài)代理
- 被代理類必須實現(xiàn)一個接口不狮,任意接口
public class Bus implements Runnable{};
- 創(chuàng)建一個類實現(xiàn)InvocationHandler蠢琳,該類用來動態(tài)代理對象進(jìn)行方法的增強(qiáng)
public class TimeInvocation implements InvocationHandler{
private Object target;//被代理對象
public TimeInvocation(Object target){
this.target=target;
}
}
- 在invoke()方法中調(diào)用被代理對象的方法柳骄,并且添加增強(qiáng)的代碼
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
long time1=System.currentTimeMillis();
//調(diào)用被代理對象的方法
method.invoke(target, args);
long time2=System.currentTimeMillis();
System.out.println(time2-time1);
return null;
}
通過Proxy.newProxyInstance(ClasLoader, Class, InvovationHandler)創(chuàng)建代理類對象
調(diào)用代理對象的方法
TimeInvocation time=new TimeInvocation(s);
Class<?> clazz=s.getClass();
Runnable s1= (Runnable)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), time);
s1.run();