注解
注解的作用矮台?
1.傳遞數(shù)據(jù)
2.標(biāo)記
自定義注解
開發(fā)步驟
創(chuàng)建一個@interface
String value();抽象方法用以接收數(shù)據(jù)
使用元注解刀闷,描述自定義注解
@Target指定注解可以加在哪里
ElementType.TYPE:可在類和接口上面
ElementType.METHOD:可方法上
ElementType.FIELD:可在屬性
@Retention指定注解在什么時(shí)候有用
RetentionPolicy.RUNTIME:注解保留到運(yùn)行時(shí)
RetentionPolicy.ClASS:注解保留到Class文件中
RetentionPolicy.SOURCE:注解保留到j(luò)ava編譯時(shí)期
@Inherited可以被繼承
jdk動態(tài)代理
被代理類必須實(shí)現(xiàn)一個接口,任意接口
public class Bus implements Runnable{}
創(chuàng)建一個類實(shí)現(xiàn)InvocationHandler团赏,該類用來對象代理對象進(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 {
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();