注解和動態(tài)代理

按照來源注解

java自帶的注解

@override
@SuppressWarnings
@Deprecated

第三方的注解

mybatis的注解
@Test

自定義注解

元注解

給注解標(biāo)示注解

@Target(value={ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Hemi {
    String value();
    int num=100;
}

@Target指定注解可以放置的位置
ElementType.TYPE:放在類上
ElementType.METHOD:放在方法上
ElementType.FIELD:放在字段上
@Retention:指定注解在什么時候有用
RetentionPolicy.RUNTIME:運(yùn)行時有用
RetentionPolicy.CLASS:編譯時有用
RetentionPolicy.RESOURCE:源文件有用
@Inherited:表示可繼承

得到注解的內(nèi)容

    Class<?> clazz=MyHemi.class;
    Hemi annotation = clazz.getAnnotation(Hemi.class);
    String value = annotation.value();
    Method method = clazz.getMethod("insert");
    Hemi annotation2 = method.getAnnotation(Hemi.class);
    String value2 = annotation2.value();
    System.out.println(value);
    System.out.println(value2);

注解的作用

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

jdk動態(tài)代理

1.被代理類必須實(shí)現(xiàn)一個接口

public class Student implements Runnable{

    @Override
    public void run() {
        System.out.println("跑步");   
        try {
            Thread.sleep(2000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

2.創(chuàng)建一個類實(shí)現(xiàn)InvocatiobHandler接口,該類用來對象代理對象進(jìn)行方法的增強(qiáng)

public class TimeUntil implements InvocationHandler{
    //將對象傳入進(jìn)來
    public Object target;
    public TimeUntil(Object target){
        this.target=target;
    }
}

3.通過Proxy.newProxyInstance(ClasLoader, Class, InvovationHandler)來創(chuàng)建代理類對象并調(diào)用代理對象的方法

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long time1 = System.currentTimeMillis();
        method.invoke(target, args);
        long time2 = System.currentTimeMillis();
        System.out.println(time2-time1);
        return null;
    }

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

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

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