Java custom class notes, and use of them

In Java framework, often using annotations, but also save a lot of things, to understand under custom annotation.

Annotations can be added to a metadata java code, classes, methods, variables, parameters, and packages can be used to modify annotations. Notes for which it modified the code and no direct effect

The first to write a comment of your own class

@Documented //会被javadoc命令识别
@Retention(RetentionPolicy.RUNTIME) //相当于作用时期,比如:运行期、编译期
@Target({ElementType.METHOD}) //相当于作用域,比如方法、类
public @interface MyValue {

    String value();
    //也可以这么写,就是说,它的默认值是hello
    //String value() default "hello";

}

And then parse the top two classes used:

public enum RetentionPolicy {
    SOURCE,
    CLASS,
    RUNTIME
}
public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,
    FIELD,
    METHOD,
    PARAMETER,
    CONSTRUCTOR,
    LOCAL_VARIABLE,
    ANNOTATION_TYPE,
    PACKAGE
}

It can be seen that two enumeration class, which is our custom annotations have some time and space scope.
Well, our custom annotation has been completed (right, top custom annotation on that piece of code), then we should look at how helpful it? It is easy ah, just as other comments, write what we need to place enough. (Right, I'm sure not kidding)

public class Person {
    
    @MyValue(value="张三")
    private String name;

    /*
    为什么要写setter和getter,很快你就会知道
     */
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Then we'll get in other places

Person person = new Person();
System.out.println(person.getName());//null

//这就很难受,按道理来说,不是应该是张三吗?

As we all know, such as the Spring framework is achieved through reflection, we simulate a "compiler class," we are on the property with a comment, so I have to use reflection to get all the properties of the class

public static void main(String[] args) throws NoSuchFieldException {
        Person person = new Person();

        //按理来说,我们是拿到这个Person.class的所有的属性,然后遍历,来挨个注入,但是这里我们明明确我们的属性名,所以就简单化了
        Field   field = Person.class.getDeclaredField("name");

        MyValue annotation = field.getAnnotation(MyValue.class);//拿到注解类

        String name = annotation.value();//这个value()就是我们在MyValue类中的的属性

        //然后我们就注入到这个类中,这时就用到了setter方法
        person.setName(name);

        System.out.println("通过自定义注解后的person的name是:" + person.getName());
    }

Yes, so we adopted the custom annotation to Person injected with a name attribute, but in practical use can not be so complicated, it's just a beginning look, we can use this "simulation compiled class" assembled into a utility class so that we can apply in practice.

Guess you like

Origin www.cnblogs.com/Lyn4ever/p/11594533.html