search
HomeJavajavaTutorialIntroduction to the definition and use of Java annotations (code examples)

This article brings you the definition and use of Java annotations (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Java annotations are used a lot in actual projects, especially after using Spring.

This article will introduce the syntax of Java annotations and examples of using annotations in Spring.

Syntax of annotations

Examples of annotations

Take the @Test annotation in Junit as an example

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

You can see the @Test annotation There are two annotations @Target() and @Retention().
This kind of annotation that annotates annotations is called meta-annotation.
It has the same meaning as the data that declares the data, which is called metadata. The format of the annotation after

is

修饰符 @interface 注解名 {   
    注解元素的声明1 
    注解元素的声明2   
}

The element of the annotation has two forms

type elementName();
type elementName() default value;  // 带默认值

Common meta-annotations

@TargetAnnotation

@Target annotation is used to limit which items the annotation can be applied to. Annotations without @Target can be applied to on any item.

You can see all items accepted by @Target

    # in the
  • java.lang.annotation.ElementType

    class ##TYPE Use

  • #FIELD on [Class, Interface, Annotation] Use ## on [Field, Enumeration Constant]

  • #METHOD

    Use

  • ## on [Method] Use
  • ## on [Parameter]

    #CONSTRUCTOR

    Use on [Constructor]
  • ##LOCAL_VARIABLE Use on [Local Variable]

  • ANNOTATION_TYPE Use

  • on [Annotation] Use on [Package]

  • TYPE_PARAMETER Introduced in Java 1.8 on [type parameters]

  • ##TYPE_USE

    on [any declared type Where] using Java 1.8, the

  • #@Test

    annotation is only allowed to be used on methods. <pre class="brush:php;toolbar:false">@Target(ElementType.METHOD) public @interface Test { ... }</pre>If you want to support multiple items, pass in multiple values.

    @Target({ElementType.TYPE, ElementType.METHOD})
    public @interface MyAnnotation { ... }
  • In addition, meta-annotations are also annotations and conform to the syntax of annotations, such as
@Target

annotations. @Target(ElementType.ANNOTATION_TYPE)

Indicates that the

@Target

annotation can only be used on annotations.

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    ElementType[] value();
}
@Retention
Annotation@RetentionSpecifies how long the annotation should be retained. The default is RetentionPolicy.CLASS

. You can see all items in java.lang.annotation.RetentionPolicy

SOURCE
is not included in the class file

  • CLASS

    Contained in the class file, the virtual machine is not loaded

  • RUNTIME

    Contained in the class file, loaded by the virtual machine, you can use the reflection API to get the

  • @Test

    annotation will be loaded into the virtual machine, you can get it through the code <pre class="brush:php;toolbar:false">@Retention(RetentionPolicy.RUNTIME) public @interface Test { ... }</pre>

    @Documented
  • Annotation

is mainly used for archiving tool identification. Annotated elements can be documented using Javadoc or similar tools.

@InheritedAnnotation

Added the annotation of the @Inherited annotation, the subclasses of the annotated class will also have this annotation

Annotation<pre class="brush:php;toolbar:false">@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface MyAnnotation { ... }</pre>Parent class

@MyAnnotation 
class Parent { ... }

SubclassChild will add

@MyAnnotation

to

Parent

Inherited

class Child extends Parent { ... }

@RepeatableAnnotationsThe annotations introduced in Java 1.8 mark the annotations as reusable. Note 1

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

Note 2<pre class="brush:php;toolbar:false">@Repeatable(MyAnnotations.class) public @interface MyAnnotation {        int value(); }</pre>Used when using

@Repeatable()

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

Not used## When using #@Repeatable()

,

@MyAnnotation

remove

@Repeatablemeta-annotation

@MyAnnotations({
    @MyAnnotation(1), 
    @MyAnnotation(2),
    @MyAnnotation(3)})
public class MyTest { ... }
This annotation is still very useful, making our code more It is much more concise. The

@ComponentScan annotation of Spring also uses this meta-annotation. Types of elements

Supported element types
8 basic data types (byte

,

short

,

char

,
    int
  • ,

    long, float, double, boolean )String

    ##Class
  • enum
  • Annotation type

  • Array (all arrays of the above types)

  • Example
  • Enumeration class

    public enum Status {
        GOOD,
        BAD
    }
  • Note 1
  • @Target(ElementType.ANNOTATION_TYPE)
    public @interface MyAnnotation1 {
        int val();
    }

    Note 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();
        
    }
  • When used, elements without default values ​​must pass values
@MyAnnotation2(
        cla = String.class,
        enu = Status.BAD,
        anno = @MyAnnotation1(val = 2),
        arr = {"a", "b"})
public class MyTest { ... }

Java

Built-in annotations

@Override

Annotations

tells the compiler that this is a method that overrides the parent class. If the parent class deletes this method, the subclass will report an error.

@DeprecatedAnnotation

indicates that the annotated element has been deprecated.

@SuppressWarnings

Annotation

Tells the compiler to ignore warnings.

@FunctionalInterface

Annotations

Annotations introduced in Java 1.8. This annotation forces the compiler javac to check whether an interface conforms to the functional interface standard.

特别的注解

有两种比较特别的注解

  • 标记注解 : 注解中没有任何元素,使用时直接是 @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> 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;
    }

}</integer>

主要工作都是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();
    }
}

> 完整项目

总结

可以看到使用注解能够写出很灵活的代码,注解也特别适合做为使用框架的一种方式。
所以学会使用注解还是很有用的,毕竟这对于上手框架或实现自己的框架都是非常重要的知识。

The above is the detailed content of Introduction to the definition and use of Java annotations (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.