java注解

 

PrintMsg.java

import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Inherited;


@Retention(RetentionPolicy.RUNTIME)
public @interface PrintMsg {
    int count() default 1;
    String name() default "my name is PrintMsg";
}

 

AnnotationTest.java

@PrintMsg(count = 2020, name = "你不填就会用默认值")
public class AnnotationTest {
    public static void main(String[] args) {
        //通过反射获取该注解
        PrintMsg annotation = AnnotationTest.class.getAnnotation(PrintMsg.class);
        if(annotation == null){
            System.out.println("null...");
            
            return;
        }
        System.out.println(annotation.count());
        System.out.println(annotation.name());
    }
}

 

build.bat

javac -encoding UTF-8 AnnotationTest.java

 

posted @ 2020-12-16 16:56  yasepix  阅读(67)  评论(0编辑  收藏  举报