自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java中注解的高級(jí)用法

開發(fā) 前端
注解本身沒有含義,主要作用是標(biāo)記目標(biāo)元素,后續(xù)拿到改標(biāo)識(shí)的元數(shù)據(jù),進(jìn)行一系列的處理。注解的使用是非常廣泛的,各種框架中都使用頻繁,基于注解可以將很多抽象功能提取出來,通過簡(jiǎn)單 的標(biāo)識(shí)來實(shí)現(xiàn)各種復(fù)雜的功能。

Annotation

注解(Annotation),也叫元數(shù)據(jù)。一種代碼級(jí)別的說明。它是JDK1.5及以后版本引入的一個(gè)特性,與類、接口、枚舉是在同一個(gè)層次。它可以聲明在包、類、字段、方法、局部變量、方法參數(shù)等的前面,用來對(duì)這些元素進(jìn)行說明,注釋。作用分類:

  1. 編寫文檔:通過代碼里標(biāo)識(shí)的元數(shù)據(jù)生成文檔【生成文檔doc文檔】
  2. 代碼分析:通過代碼里標(biāo)識(shí)的元數(shù)據(jù)對(duì)代碼進(jìn)行分析【使用反射】
  3. 編譯檢查:通過代碼里標(biāo)識(shí)的元數(shù)據(jù)讓編譯器能夠?qū)崿F(xiàn)基本的編譯檢查【Override】

注解不會(huì)改變程序的語義,只是作為注解(標(biāo)識(shí))存在,我們可以通過反射機(jī)制編程實(shí)現(xiàn)對(duì)這些元數(shù)據(jù)(用來描述數(shù)據(jù)的數(shù)據(jù))的訪問

分類

  • 運(yùn)行期注解 程序運(yùn)行時(shí)才會(huì)被解析到的注解,一般通過反射機(jī)制來實(shí)現(xiàn),很多框架中都會(huì)用到,經(jīng)常會(huì)看到一個(gè)注解和一些簡(jiǎn)單的配置來實(shí)現(xiàn)非常復(fù)雜的功能
  • 編譯期注解 一般用來解析類型元數(shù)據(jù),根據(jù)特定注解解析并生成代碼,或者生成一些描述性文件,比如properties、json等,比如為Pojo生成getter和setter方法

關(guān)鍵注解

@java.lang.annotation.Retention定義注解的有效時(shí)期

相關(guān)參數(shù):RetentionPolicy.SOURCE: 編譯期生效,編譯器會(huì)丟棄,編譯后的class文件并不包含該注解 RetentionPolicy.CLASS:  注解會(huì)被保留在class文件中,但是運(yùn)行期不會(huì)生效,被JVM忽略 RetentionPolicy.RUNTIME: 注解會(huì)被保留在class文件中,并且會(huì)在運(yùn)行期生效,JVM會(huì)讀取

@Target定義注解作用對(duì)象,也就是注解是可以用在類、方法、參數(shù)還是其他等待

相關(guān)參數(shù):ElementType.TYPE: 該注解只能運(yùn)用到Class, Interface, enum上 ElementType.FIELD: 該注解只能運(yùn)用到Field上 ElementType.METHOD: 該注解只能運(yùn)用到方法上 ElementType.PARAMETER: 該注解只能作用在參數(shù)上 ElementType.CONSTRUCTOR: 該注解只能作用在構(gòu)造方法上 ElementType.LOCAL_VARIABLE: 該注解作用在地變量或catch語句 ElementType.ANNOTATION_TYPE: 該注解只能作用在注解上 ElementType.PACKAGE: 該注解只能用在包上

Java中常見的內(nèi)置注解:

  • @Override
  • @Deprecated
  • @SuppressWarnings

繼承關(guān)系

  • @Inherited

如果某個(gè)注解上有@Inherited注解,當(dāng)查找該類型的注解時(shí),會(huì)先查找目標(biāo)類型是否存在注解,如果有,直接返回;否則,繼續(xù)在父類上尋找注解, 停止的條件為在父類上找到該類型的注解或者父類為Object類型。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface ClassMapper {

}

下面的示例中,如果ClassMapper沒有@Inherited修飾,則返回null

Child.class.getAnnotation(ClassMapper.class);
@Slf4j
public class ExtendAnnotationTests {
    @ClassMapper
    public class Demo { }

    public class Child extends Demo{  }
}
  • 元注解(注解上的注解)

我們知道,在Spring中,注解@Service與@Component都是用來標(biāo)記類,交由Spring容器管理其對(duì)應(yīng)的Bean,是結(jié)果是等效的。主要是Spring將注解和元注解進(jìn)行了合并

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Mapper {

}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Mapper
public @interface ClassMapper {

}

通過下面的方法可以拿到元注解,從而進(jìn)行其他擴(kuò)展。

public class Tests {
    @Test
    public void test(){
        ClassMapper classMapper = Demo.class.getAnnotation(ClassMapper.class);
        log.info("classMapper: {}", classMapper);
        Mapper mapper = classMapper.annotationType().getAnnotation(Mapper.class);
        log.info("mapper: {}", mapper);
    }
}

示例

示例主要針對(duì)@java.lang.annotation.Retention參數(shù)的三種情況,了解注解是生效時(shí)期:

RetentionPolicy.RUNTIME

該示例實(shí)現(xiàn)通過自定義注解@SystemProperty,實(shí)現(xiàn)為對(duì)象字段設(shè)置系統(tǒng)屬性

  1. 定義注解@SystemProperty
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface SystemProperty {

    String value();
}
  1. 定義對(duì)象工廠

主要作用是在運(yùn)行時(shí)解析注解@SystemProperty,并實(shí)現(xiàn)系統(tǒng)屬性注入的邏輯。前面說到,注解的作用主要是標(biāo)記,針對(duì)RetentionPolicy.RUNTIME類型的注解,一般是在運(yùn)行時(shí) 通過反射實(shí)現(xiàn)注解標(biāo)識(shí)的類、字段或方法等等元數(shù)的處理過程。

ObjectFactory是一個(gè)對(duì)象生產(chǎn)工廠,這樣我們可以在運(yùn)行期解析目標(biāo)對(duì)象中的是否有@SystemProperty標(biāo)識(shí)的字段,并對(duì)該字段進(jìn)行值的設(shè)定,這樣式該注解設(shè)計(jì)的初衷,但是 實(shí)現(xiàn)需要我們根據(jù)需求實(shí)現(xiàn)

@Slf4j
public class ObjectFactory {
    // 省略 ...
  
    public static <T> T getObject(Class<T> type, Object... args){
        Constructor<T> constructor = findTypeConstructor(type, args);
        T object = constructor.newInstance(args);
        // 通過反射找到對(duì)象中@SystemProperty的字段,并根據(jù)其設(shè)置參數(shù)將系統(tǒng)屬性設(shè)定到該對(duì)象字段中
        processFieldAnnotations(object, type, SystemProperty.class);
        return object;
    }
    
    // 省略 ...  
}
  1. 驗(yàn)證
    可以查看對(duì)象中被注解標(biāo)識(shí)的屬性被設(shè)置上去了
@Slf4j
public class RuntimeAnnotationTests {
    @Test
    public void run(){
        Demo demo = ObjectFactory.getObject(Demo.class);
        log.info(">> result: {}", demo.user);
    }

    @Data
    public static class Demo{
        @SystemProperty("user.name")
        private String user;
    }
}

RetentionPolicy.CLASS

該示例主要實(shí)現(xiàn),編譯器判斷通過@FinalClass注解標(biāo)記的類是否為final類型

  1. 定義注解
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
@Documented
public @interface FinalClass {

}
  1. 編寫AbstractProcessor的實(shí)現(xiàn)
@SupportedAnnotationTypes({FinalClassProcessor.FINAL_CLASS})
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@AutoService(Processor.class)
public class FinalClassProcessor extends AbstractProcessor {

    public static final String FINAL_CLASS = "com.sucl.blog.jdk.annotation.compile.FinalClass";
    
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        TypeElement annotationType = this.processingEnv.getElementUtils().getTypeElement(FINAL_CLASS);
        if( annotationType != null ){
            for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) {
                if( element instanceof TypeElement ){
                    TypeElement typeElement = (TypeElement) element;
                    if( !typeElement.getModifiers().contains(Modifier.FINAL) ){
                        String message = String.format("類【%s】必須為final類型", typeElement);
                        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message);
                    }
                }
            }
        }
        return true;
    }
}
  1. 使FinalClassProcessor生效
  • 基于google auto-service
    3.1 添加依賴
<dependency>
      <groupId>com.google.auto.service</groupId>
      <artifactId>auto-service</artifactId>
      <version>1.1.0</version>
    </dependency>

3.2 在Processor通過注解@AutoService標(biāo)識(shí)

@AutoService(Processor.class)
public class FinalClassProcessor extends AbstractProcessor{}
  • 基于maven插件
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <annotationProcessors>
            <annotationProcessor>
                com.sucl.blog.jdk.annotation.compile.FinalClassProcessor
            </annotationProcessor>
        </annotationProcessors>
    </configuration>
</plugin>
  1. 驗(yàn)證

打包,在項(xiàng)目中引入該jar,定義一個(gè)類,類似下面這樣,當(dāng)該類沒有final修飾時(shí),通過maven install命令,可以看到控制臺(tái)打印自定義的錯(cuò)誤信息

@FinalClass
public final class ProcessorFinder {}


圖片


注意

RetentionPolicy.CLASS的使用需要達(dá)打成jar包才行,不然無法再編譯時(shí)處理注解

RetentionPolicy.SOURCE

定義一個(gè)注解,通過打包后的結(jié)果觀察該注解的狀態(tài)

  1. 定義注解
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@Documented
public @interface System {
    
}
  1. 定義測(cè)試類,并通過@System修飾
@System
public class SystemProvider {

}
  1. 打包,借助maven-source-plugin同時(shí)將源碼打包
<plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <version>3.2.1</version>
            <executions>
                <execution>
                    <id>attach-sources</id>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
  1. 在源碼包中,可以看到該注解仍然存在,但是class文件中卻沒有

在基于Spring Boot開發(fā)項(xiàng)目時(shí),我們一般通過 @ConfigurationProperties 配合 spring-boot-configuration-processor,可以實(shí)現(xiàn)在項(xiàng)目打包時(shí) 生成一個(gè)spring-configuration-metadata.json的配置描述文件,這樣在編寫application.yml配置時(shí),就會(huì)得到配置提示,其實(shí)現(xiàn)方式就是基于 ConfigurationMetadataAnnotationProcessor,

結(jié)束語

注解本身沒有含義,主要作用是標(biāo)記目標(biāo)元素,后續(xù)拿到改標(biāo)識(shí)的元數(shù)據(jù),進(jìn)行一系列的處理。注解的使用是非常廣泛的,各種框架中都使用頻繁,基于注解可以將很多抽象功能提取出來,通過簡(jiǎn)單 的標(biāo)識(shí)來實(shí)現(xiàn)各種復(fù)雜的功能。

責(zé)任編輯:武曉燕 來源: Java技術(shù)指北
相關(guān)推薦

2020-12-02 11:56:16

Java注解Excel

2023-07-26 00:32:33

注解抽象spring

2023-04-09 23:25:30

Java注解元注解

2022-08-31 10:13:04

C語言代碼

2015-03-09 14:18:41

Java注釋原則

2021-07-15 06:43:12

Jackson注解用法

2020-02-04 14:53:22

git前端小抄

2022-07-03 08:06:40

JavaScript語言代碼

2017-03-10 10:16:37

PythonRequests庫

2024-10-28 21:02:36

消息框應(yīng)用程序

2022-02-19 07:41:36

Bean注解項(xiàng)目

2022-02-20 07:28:13

Spring注解用法

2024-01-02 15:41:04

CythonPython語言

2021-08-10 09:57:27

JavaScriptPromise 前端

2010-09-30 16:17:13

2024-11-21 12:55:11

Promise異步操作

2022-12-06 08:37:43

2023-11-23 19:27:56

2024-08-13 15:23:37

2021-12-30 12:30:01

Java注解編譯器
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)