Java注解

定义

Java程序的一种特殊“注释”——注解(Annotation)

什么是注解(Annotation)?注解是放在Java源码的类、方法、字段、参数前的一种特殊“注释”:

// this is a component:
@Resource("hello")
public class Hello {
    @Inject
    int n;

    @PostConstruct
    public void hello(@Param String name) {
        System.out.println(name);
    }
 
    @Override
    public String toString() {
        return "Hello";
    }
}

注释会被编译器直接忽略,注解则可以被编译器打包进入class文件,因此,注解是一种用作标注的“元数据”。

注解的作用

注解分三种:

  1. 编译器使用的注解,不会被编译进.class文件
    • @Override:让编译器检查该方法是否正确地实现了覆写;
    • @SuppressWarnings:告诉编译器忽略此处代码产生的警告。
  2. 第二类是由工具处理.class文件使用的注解,比如有些工具会在加载class的时候,对class做动态修改,实现一些特殊的功能。
  3. 第三类是在程序运行期能够读取的注解,它们在加载后一直存在于JVM中,这也是最常用的注解。

自定义注解

自定义注解要配合注解工具类使用,通过反射拿到方法有没有注解,通过反射把注解的值注入到对象中。

定义:

import java.lang.annotation.*;

@Documented
@Inherited
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Init {
    public String value() default "";
}

使用:

public class User {
    private String name;
    private String age;

    public String getName() {
        return name;
    }

    @Init(value = "yang")
    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    @Init(value = "99")
    public void setAge(String age) {
        this.age = age;
    }
}

注解工具类:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class UserFactory {
    public static User create() throws InvocationTargetException, IllegalAccessException {
        User user = new User();

        Method[] methods = User.class.getMethods();

        try {
            for (Method method: methods){
                if(method.isAnnotationPresent(Init.class)){
                    Init init = method.getAnnotation(Init.class);
                    method.invoke(user, init.value());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }
}

测试:

import java.lang.reflect.InvocationTargetException;

public class MyTest {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        User user = UserFactory.create();
        System.out.println(user.getAge());
        System.out.println(user.getName());
    }
}
原文地址:https://www.cnblogs.com/punnpkin/p/13573881.html