注解

注解

注解的作用?

1.傳遞數(shù)據(jù)
2.標(biāo)記

自定義注解

開(kāi)發(fā)步驟

創(chuàng)建一個(gè)@interface
String value();抽象方法用以接收數(shù)據(jù)
使用元注解,描述自定義注解
@Target指定注解可以加在哪里

ElementType.TYPE:可在類(lèi)和接口上面

ElementType.METHOD:可方法上

ElementType.FIELD:可在屬性

@Retention指定注解在什么時(shí)候有用

RetentionPolicy.RUNTIME:注解保留到運(yùn)行時(shí)

RetentionPolicy.ClASS:注解保留到Class文件中

RetentionPolicy.SOURCE:注解保留到j(luò)ava編譯時(shí)期

@Inherited可以被繼承

jdk動(dòng)態(tài)代理

被代理類(lèi)必須實(shí)現(xiàn)一個(gè)接口,任意接口
public class Bus implements Runnable{}
創(chuàng)建一個(gè)類(lèi)實(shí)現(xiàn)InvocationHandler,該類(lèi)用來(lái)對(duì)象代理對(duì)象進(jìn)行方法的增強(qiáng)

public class TimeInvocation implements InvocationHandler{
    private Object target;//被代理對(duì)象
    public TimeInvocation(Object target){
        this.target=target;
    }
}

在invoke()方法中調(diào)用被代理對(duì)象的方法,并且添加增強(qiáng)的代碼

   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long time1=System.currentTimeMillis();
        //調(diào)用被代理對(duì)象的方法
        method.invoke(target, args);
        long time2=System.currentTimeMillis();
        System.out.println(time2-time1);
        return null;
    }

通過(guò)Proxy.newProxyInstance(ClasLoader, Class, InvovationHandler)創(chuàng)建代理類(lèi)對(duì)象
調(diào)用代理對(duì)象的方法

        TimeInvocation time=new TimeInvocation(s);
        Class<?> clazz=s.getClass();
        Runnable s1= (Runnable)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), time);
        s1.run();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容