Java之註解的定義及使用

Java的註解在實際項目中使用得非常的多,特別是在使用了Spring之後。
本文會介紹Java註解的語法,以及在Spring中使用註解的例子。

註解的語法

註解的例子

Junit中的@Test註解爲例

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
    long timeout() default 0L;
}

可以看到@Test註解上有@Target()@Retention()兩個註解。
這種註解了註解的註解,稱之爲元註解
跟聲明瞭數據的數據,稱爲元數據是一種意思。

之後的註解的格式是

修飾符 @interface 註解名 {   
    註解元素的聲明1 
    註解元素的聲明2   
}

註解的元素聲明有兩種形式

type elementName();
type elementName() default value;  // 帶默認值

常見的元註解

@Target註解

@Target註解用於限制註解能在哪些項上應用,沒有加@Target的註解可以應用於任何項上。

java.lang.annotation.ElementType類中可以看到所有@Target接受的項

  • TYPE 在【類、接口、註解】上使用
  • FIELD 在【字段、枚舉常量】上使用
  • METHOD 在【方法】上使用
  • PARAMETER 在【參數】上使用
  • CONSTRUCTOR 在【構造器】上使用
  • LOCAL_VARIABLE 在【局部變量】上使用
  • ANNOTATION_TYPE 在【註解】上使用
  • PACKAGE 在【包】上使用
  • TYPE_PARAMETER 在【類型參數】上使用 Java 1.8 引入
  • TYPE_USE 在【任何聲明類型的地方】上使用 Java 1.8 引入

@Test註解只允許在方法上使用。

@Target(ElementType.METHOD)
public @interface Test { ... }

如果要支持多項,則傳入多個值。

@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation { ... }

此外元註解也是註解,也符合註解的語法,如@Target註解。
@Target(ElementType.ANNOTATION_TYPE)表明@Target註解只能使用在註解上。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    ElementType[] value();
}

@Retention註解

@Retention指定註解應該保留多長時間,默認是RetentionPolicy.CLASS
java.lang.annotation.RetentionPolicy可看到所有的項

  • SOURCE 不包含在類文件中
  • CLASS 包含在類文件中,不載入虛擬機
  • RUNTIME 包含在類文件中,由虛擬機載入,可以用反射API獲取

@Test註解會載入到虛擬機,可以通過代碼獲取

@Retention(RetentionPolicy.RUNTIME)
public @interface Test { ... }

@Documented註解

主要用於歸檔工具識別。被註解的元素能被Javadoc或類似的工具文檔化。

@Inherited註解

添加了@Inherited註解的註解,所註解的類的子類也將擁有這個註解

註解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation { ... }

父類

@MyAnnotation 
class Parent { ... }

子類Child會把加在Parent上的@MyAnnotation繼承下來

class Child extends Parent { ... }

@Repeatable註解

Java 1.8 引入的註解,標識註解是可重複使用的。

註解1

public @interface MyAnnotations {   
    MyAnnotation[] value();   
}

註解2

@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {   
    int value();
}

有使用@Repeatable()時的使用

@MyAnnotation(1)
@MyAnnotation(2)
@MyAnnotation(3)
public class MyTest { ... }

沒使用@Repeatable()時的使用,@MyAnnotation去掉@Repeatable元註解

@MyAnnotations({
    @MyAnnotation(1), 
    @MyAnnotation(2),
    @MyAnnotation(3)})
public class MyTest { ... }    

這個註解還是非常有用的,讓我們的代碼變得簡潔不少,
Spring@ComponentScan註解也用到這個元註解。

元素的類型

支持的元素類型

  • 8種基本數據類型(byteshortcharintlongfloatdoubleboolean
  • String
  • Class
  • enum
  • 註解類型
  • 數組(所有上邊類型的數組)

例子

枚舉類

public enum Status {
    GOOD,
    BAD
}

註解1

@Target(ElementType.ANNOTATION_TYPE)
public @interface MyAnnotation1 {
    int val();
}

註解2

@Target(ElementType.TYPE)
public @interface MyAnnotation2 {
    
    boolean boo() default false;
    
    Class<?> cla() default Void.class;
    
    Status enu() default Status.GOOD;
    
    MyAnnotation1 anno() default @MyAnnotation1(val = 1);
    
    String[] arr();
    
}

使用時,無默認值的元素必須傳值

@MyAnnotation2(
        cla = String.class,
        enu = Status.BAD,
        anno = @MyAnnotation1(val = 2),
        arr = {"a", "b"})
public class MyTest { ... }

Java內置的註解

@Override註解

告訴編譯器這個是個覆蓋父類的方法。如果父類刪除了該方法,則子類會報錯。

@Deprecated註解

表示被註解的元素已被棄用。

@SuppressWarnings註解

告訴編譯器忽略警告。

@FunctionalInterface註解

Java 1.8 引入的註解。該註釋會強制編譯器javac檢查一個接口是否符合函數接口的標準。

特別的註解

有兩種比較特別的註解

  • 標記註解 : 註解中沒有任何元素,使用時直接是 @XxxAnnotation, 不需要加括號
  • 單值註解 : 註解只有一個元素,且名字爲value,使用時直接傳值,不需要指定元素名@XxxAnnotation(100)

利用反射獲取註解

JavaAnnotatedElement接口中有getAnnotation()等獲取註解的方法。
MethodFieldClassPackage等類均實現了這個接口,因此均有獲取註解的能力。

例子

註解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
public @interface MyAnno {   
    String value();   
}

被註解的元素

@MyAnno("class")
public class MyClass {
    
    @MyAnno("feild")
    private String str;
    
    @MyAnno("method")
    public void method() { }
    
}

獲取註解

public class Test {
    
    public static void main(String[] args) throws Exception {
    
        MyClass obj = new MyClass();
        Class<?> clazz = obj.getClass();
        
        // 獲取對象上的註解
        MyAnno anno = clazz.getAnnotation(MyAnno.class);
        System.out.println(anno.value());
        
        // 獲取屬性上的註解
        Field field = clazz.getDeclaredField("str");
        anno = field.getAnnotation(MyAnno.class);
        System.out.println(anno.value());
        
        // 獲取方法上的註解
        Method method = clazz.getMethod("method");
        anno = method.getAnnotation(MyAnno.class);
        System.out.println(anno.value());
    }
    
}

Spring中使用自定義註解

註解本身不會有任何的作用,需要有其他代碼或工具的支持纔有用。

需求

設想現有這樣的需求,程序需要接收不同的命令CMD
然後根據命令調用不同的處理類Handler
很容易就會想到用Map來存儲命令和處理類的映射關係。

由於項目可能是多個成員共同開發,不同成員實現各自負責的命令的處理邏輯。
因此希望開發成員只關注Handler的實現,不需要主動去Map中註冊CMDHandler的映射。

最終效果

最終希望看到效果是這樣的

@CmdMapping(Cmd.LOGIN)
public class LoginHandler implements ICmdHandler {
    @Override
    public void handle() {
        System.out.println("handle login request");
    }
}

@CmdMapping(Cmd.LOGOUT)
public class LogoutHandler implements ICmdHandler {
    @Override
    public void handle() {
        System.out.println("handle logout request");
    }
}

開發人員增加自己的Handler,只需要創建新的類並註上@CmdMapping(Cmd.Xxx)即可。

具體做法

具體的實現是使用Spring和一個自定義的註解
定義@CmdMapping註解

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface CmdMapping {
    int value();   
}

@CmdMapping中有一個int類型的元素value,用於指定CMD。這裏做成一個單值註解。
這裏還加了Spring@Component註解,因此註解了@CmdMapping的類也會被Spring創建實例。

然後是CMD接口,存儲命令。

public interface Cmd {
    int REGISTER = 1;
    int LOGIN    = 2;
    int LOGOUT   = 3;
}

之後是處理類接口,現實情況接口會複雜得多,這裏簡化了。

public interface ICmdHandler { 
    void handle();   
}

上邊說過,註解本身是不起作用的,需要其他的支持。下邊就是讓註解生效的部分了。
使用時調用handle()方法即可。

@Component
public class HandlerDispatcherServlet implements 
    InitializingBean, ApplicationContextAware {

    private ApplicationContext context;

    private Map<Integer, ICmdHandler> handlers = new HashMap<>();
    
    public void handle(int cmd) {
        handlers.get(cmd).handle();
    }
    
    public void afterPropertiesSet() {
        
        String[] beanNames = this.context.getBeanNamesForType(Object.class);

        for (String beanName : beanNames) {
            
            if (ScopedProxyUtils.isScopedTarget(beanName)) {
                continue;
            }
            
            Class<?> beanType = this.context.getType(beanName);
            
            if (beanType != null) {
                
                CmdMapping annotation = AnnotatedElementUtils.findMergedAnnotation(
                        beanType, CmdMapping.class);
                
                if(annotation != null) {
                    handlers.put(annotation.value(), (ICmdHandler) context.getBean(beanType));
                }
            }
        }
        
    }

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {   
        this.context = applicationContext;
    }

}

主要工作都是Spring做,這裏只是將實例化後的對象putMap中。

測試代碼

@ComponentScan("pers.custom.annotation")
public class Main {

    public static void main(String[] args) {
        
        AnnotationConfigApplicationContext context 
            = new AnnotationConfigApplicationContext(Main.class);
            
        HandlerDispatcherServlet servlet = context.getBean(HandlerDispatcherServlet.class);
        
        servlet.handle(Cmd.REGISTER);
        servlet.handle(Cmd.LOGIN);
        servlet.handle(Cmd.LOGOUT);

        context.close();
    }
}

> 完整項目

總結

可以看到使用註解能夠寫出很靈活的代碼,註解也特別適合做爲使用框架的一種方式。
所以學會使用註解還是很有用的,畢竟這對於上手框架或實現自己的框架都是非常重要的知識。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章