【Java基礎】Java註解簡單入門

來源:互聯網
上載者:User

標籤:ati   users   his   get   gil   pos   first   xxx   定義   

註解簡單來說就是配置,是特別的配置,之前常用的設定檔,可以用註解替換。然後通過反射去擷取註解的資訊。

如何定義一個註解

你在IDE中建立一個註解定義,是這樣的結構的:

package com.nicchagil.exercise.springbootexercise.annotation;public @interface MyFirstAnnotation {}

然後大概有4個對上述結構加上一些配置,當然,這配置是以註解的形式添加的=_=!

此註解使用在哪裡

此註解會應用的哪裡,可通過如下配置:

保留在什麼時候

保留到什麼時候:

註解體現在文檔中

@Documented

子類是否繼承父類的註解

@Inherited

用反射擷取註解的資訊

我們先定義一個註解:

package com.nicchagil.exercise.springbootexercise.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface PojoPostProcessing {        public Class targetClass();        public String[] whiteProperties();}

使用註解,比如這裡我設定到一個方法上:

    @PojoPostProcessing(targetClass=User.class, whiteProperties={"name"})    public List<User> selectXxx(String id) {        ......    }

反射擷取註解的資訊:

    @Test    public void test() throws NoSuchMethodException, SecurityException, ClassNotFoundException {        Class clazz = Class.forName("com.nicchagil.exercise.springbootexercise.service.UserService");                Method method = clazz.getMethod("selectXxx", String.class);                boolean isAnnotationPresent = method.isAnnotationPresent(PojoPostProcessing.class);        if (!isAnnotationPresent) {            return;        }                PojoPostProcessing dpp = (PojoPostProcessing)method.getAnnotation(PojoPostProcessing.class);        this.logger.info("dpp : {}", dpp);    }

日誌:

dpp : @com.nicchagil.exercise.springbootexercise.annotation.PojoPostProcessing(targetClass=class com.nicchagil.exercise.springbootexercise.mapper.entity.User, whiteProperties=[name])

【Java基礎】Java註解簡單入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.