自定义注解学习

自定义学习地址https://www.cnblogs.com/huojg-21442/p/7239846.html

                         https://v.qq.com/x/page/c0350vubgk7.html

自定义注解应该分类二部分,一部分为定义。还有一本分为解析。如果你光定义不解析,其实没毛用。通过解析的注解规则相应的做一下程序处理。我这里就是定义了一下注解,和解析了一下注解。没有做程序的处理。

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 
 * 这个作用于类(此注解为自定类的注解)
 * @author wb-llp368504
 * @version $Id: ZDYCAnnotation.java, v 0.1 2018年8月14日 下午3:20:27 wb-llp368504 Exp $
 */
@Target(value = {ElementType.TYPE})
@Retention(value=RetentionPolicy.RUNTIME)
public @interface ZDYCAnnotation {
    String value();
}

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 
 * 这个作用于属性(此注解为自定属性的注解)
 * @author wb-llp368504
 * @version $Id: ZDYCAnnotation.java, v 0.1 2018年8月14日 下午3:20:27 wb-llp368504 Exp $
 */
@Target(value=ElementType.FIELD)
@Retention(value=RetentionPolicy.RUNTIME)
public @interface ZDYFAnnotation {
    int length();
    String name();
    String type();
}
package annotation;
@ZDYCAnnotation(value="zdyzj")
public class ZDYZJ {
    @ZDYFAnnotation(length=10,type="String",name="name")
    private String name;
    @ZDYFAnnotation(length=10,type="int",name="age")
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

package annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class AnnotationTest {
/**
 * 自定定义注解测试类
 * 
 * @param args
 */
public static void main(String[] args) {
     String classpath="annotation.ZDYZJ";
    try {
      Class<?>  className = Class.forName(classpath);
      //得到类中定义的注解,(不包括属性和方法)
      Annotation[] annotations = className.getAnnotations();
      for(Annotation ac:annotations){
          System.out.println(ac);
      }
      //通过具体的类找到注解类
      ZDYCAnnotation annotation =(ZDYCAnnotation)className.getAnnotation(ZDYCAnnotation.class);
      //打印类中关于注解类定义规则的value值
      System.out.println(annotation.value());
      //通过类得到属性对象的集合
      Field[] fields = className.getDeclaredFields();
      //遍历类中所有的属性对象
      for(Field field:fields){
          //通过具体的类找到注解类
          ZDYFAnnotation ZDYFAnnotation = field.getAnnotation(ZDYFAnnotation.class);
        //打印类中关于注解类定义规则的值
          System.out.println(ZDYFAnnotation.type());
          System.out.println(ZDYFAnnotation.name());
          System.out.println(ZDYFAnnotation.length());
      }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
 }
}

猜你喜欢

转载自blog.csdn.net/liliping28/article/details/81669979