java自定义注解与反射

java注解与反射
一、Java中提供了四种元注解,专门负责注解其他的注解,分别如下
  1、@Retention元注解,表示需要在什么级别保存该注释信息(生命周期)。可选的RetentionPoicy参数包括:
    RetentionPolicy.SOURCE: 停留在java源文件,编译器被丢掉
    RetentionPolicy.CLASS:停留在class文件中,但会被VM丢弃(默认)
    RetentionPolicy.RUNTIME:内存中的字节码,VM将在运行时也保留注解,因此可以通过反射机制读取注解的信息
  2、@Target元注解,默认值为任何元素,表示该注解用于什么地方。可用的ElementType参数包括
    ElementType.CONSTRUCTOR: 构造器声明
    ElementType.FIELD: 成员变量、对象、属性(包括enum实例)
    ElementType.LOCAL_VARIABLE: 局部变量声明
    ElementType.METHOD: 方法声明
    ElementType.PACKAGE: 包声明
    ElementType.PARAMETER: 参数声明
    ElementType.TYPE: 类、接口(包括注解类型)或enum声明
  3、@Documented将注解包含在JavaDoc中
  4、@Inheried允许子类继承父类中的注解
二、注解的定义
  1、注解定义的格式
    public @interface FieldMeta {}

package com.http.model;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;

@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到  
@Target({ElementType.FIELD})//定义注解的作用目标**作用范围字段、枚举的常量/方法  
@Documented//说明该注解将被包含在javadoc中
public @interface FieldMeta {
    String name() default ""; 
    String description() default "";
} 


  2、注解在实体类中的应用
    @FieldMeta(name="序列号",description="")
    private String id;
    @FieldMeta(name="姓名",description="")
    private String title;

package com.http.model;

public class ModelTest {
    @FieldMeta(name="序列号",description="")
    private String    id;
    @FieldMeta(name="标题",description="标题信息描述")  
    private String    title;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
}

三、注解的遍历反射

    //反射获取对象属性名称及注解信息
    public static void getField(){       
        try {
            Class clazz= Class.forName("com.http.model.HttpRequest");
            Field[] field=clazz.getDeclaredFields();
            //System.out.println(field.length);
            for(Field f:field){
                boolean isExist=f.isAnnotationPresent(FieldMeta.class);
                if(isExist){
                    FieldMeta tt=f.getAnnotation(FieldMeta.class);
                    System.out.println("--注解:"+tt.id()+"  "+tt.name());
                }
                System.out.println(f.getName());
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
    

  //反射获取对象方法名称
  public static void getMethod(){ try { Class clazz = Class.forName("com.http.model.HttpRequest"); Method[] method=clazz.getDeclaredMethods(); System.out.println(method.length); for(Method f:method){ System.out.println(f.getName()); //获取方法名 } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
原文地址:https://www.cnblogs.com/web369/p/4729111.html