java 自定义注解

date[2019-06-11]

自己定义注解

Description 注解

package edu.anno;
import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
    String value();
}

Person.java

package edu.anno;
public interface Person {
    String getName();
}

Child 添加注解

package edu.anno;

@Description("I am class Annotation")
public class Child implements Person {
    @Override
    @Description("I am method Annotation")
    public String getName() {
        return null;
    }

    @Override
    public String toString() {
        return super.toString();
    }
}

AnnotionParse 解析注解

package edu.anno;

import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Method;

public class AnnotionParse {
    public static void main(String[] args) {
        try {
            /*1.通过类名加载类*/
            Class clazz = Class.forName("edu.anno.Child");

            /*2.判断注解是否存在*/
            showAnnotion(clazz,Description.class);
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                showAnnotion(method,Description.class);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void showAnnotion(GenericDeclaration genericDeclaration,Class descriptionClass){
        /*2.判断注解是否存在*/
        boolean annotationPresent = genericDeclaration.isAnnotationPresent(descriptionClass);
        if(annotationPresent){
            /*3.如果注解存在,获得注解并取得其值*/
            final Description annotation = genericDeclaration.getAnnotation(descriptionClass);
            System.out.println(annotation.value());
        }
    }
}

运行结果

I am class Annotation
I am method Annotation

你可能感兴趣的:(java 自定义注解)