注解

自定義注解

public @interface User{
    
    String name() default "";
    
    int age();
}
@User(age = 10)
class Demo{
    
}

使用注解時(shí),如果屬性有默認(rèn)值可以不用賦值。

public @interface User{
    
    String name() default "";
    
    String value() default "";
}
@User("123")
class Demo{
    
}

使用注解時(shí),如果只給value屬性賦值可以省略value=

注解屬性的類型

1、8種基本類型
2、string
3、Enum
4、class
5、注解類型
6、以上5種的一維數(shù)組

public @interface User{
    int age();
    
    String name();
    
    MyEnum myEnum();
    
    Class a();
    
    MyAnno no();
    
    String[] arr();
}
enum MyEnum{
    A,B,C
}

@interface MyAnno{

    
}
@User(age = 10,name = "tom",myEnum = MyEnum.A,a = String.class,no = @MyAnno,arr = {"1","2","3"})
class Demo{
    
}

數(shù)組類型如果只有一個(gè)值可以省略{}

注解的作用目標(biāo)限定

@Target(value = {ElementType.METHOD,ElementType.FIELD})
public @interface User{
    
}

使用@Target注解限定注解放的位置。

保留策略

  • 源代碼文件(SOURCE):只在源代碼中存在,編譯時(shí)被忽略
  • 字節(jié)碼文件(CLASS):在源代碼存在,編譯時(shí)會(huì)把注解信息放到class文件,但在JVM加載類時(shí),會(huì)忽略注解!
  • JVM中(RUNTIME):注解在源代碼、字節(jié)碼中存在,并在JVM加載類時(shí)會(huì)把注解加載到內(nèi)存中(是唯一可以反射的注解?。?/li>
@Retention(RetentionPolicy.RUNTIME)
public @interface User{
    
}

使用@Retention注解,限定保留策略

反射獲得注解

@Retention(RetentionPolicy.RUNTIME)
public @interface User{
    String name();
}
@User(name="tom")
class Demo{
    @User(name="jack")
    public void demo() {
        
    }
}

    public static void main(String[] args) {
        // 獲得作用目標(biāo)
        Class<Demo> c=Demo.class;
        // 獲得注解
        User user=c.getAnnotation(User.class);
        System.out.println(user.name());
        // 獲得所有注解
        Annotation[] arr =c.getAnnotations();
    }

上面是獲得類的注解,接下來(lái)獲得方法上的注解

    public static void main(String[] args) throws NoSuchMethodException, SecurityException {
        // 獲得作用目標(biāo)
        Class<Demo> c=Demo.class;
        Method method=c.getMethod("demo");
        // 獲得注解
        User user=method.getAnnotation(User.class);
        System.out.println(user.name());
        // 獲得所有注解
        Annotation[] arr =c.getAnnotations();
    }
?著作權(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ù)。

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