zoukankan      html  css  js  c++  java
  • 自定义简单注解并获取值

    1、自定义注解Car_color 

    package com.dist.annotation;
    
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    //@Target(ElementType.PARAMETER)  //表示这个注解的只适用于属性,也可以写多个({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
    @Retention(RetentionPolicy.RUNTIME) //表示注解只在执行期起作用
    public @interface Car_color {
        //返回值String就是参数的类型,只能是基本类型
        //这里用default默认参数是“白色”
        String color() default "白色";  //color方法其实是声明了一个配置参数
    
    }
    

    2、将注解带到类或接口或字段或方法上

    //@Car_color(color="黑色")
    public class Car {
        @Car_color(color="黑色") 
        private String color;
    
    }

    3、获取方法

    1)类上注解获取值

    public class Test {
    
        public static void main(String[] args) throws ClassNotFoundException {
            Class cls=Class.forName("com.dist.annotation.Car");  //获取类对象
    
            Car_color annotation = (Car_color) cls.getAnnotation(Car_color.class);
            System.out.println(annotation.color());
    
        }
    }
    

    2)获取字段上的

    public class Test {
    
        public static void main(String[] args) throws ClassNotFoundException {
            Class cls=Class.forName("com.dist.annotation.Car");  //获取类对象
    
            Field[] field=cls.getDeclaredFields();          //获取类的属性数组
            for(Field f:field){                             //循环属性
                if(f.isAnnotationPresent(Car_color.class)){ //获取属性的注解,并判断是否是Car_color.class注解
                    Car_color car=f.getAnnotation(Car_color.class);     //获取Car_color注解对象
                    System.out.println("汽车颜色:"+car.color());            //输出注解的color配置参数
                }
            }
    
        }
    }
    
  • 相关阅读:
    win10安装mysql5.6,mysql启动时,闪退
    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    textarea输入框随内容撑开高度
    jQuery插件写法
    .net APIHelper client获取数据
    .net XmlHelper xml帮助类
    .net JsonHelper json帮助类
    .net WebAPI返回xml、json格式
    VMware Workstation Pro 14 序列号
    embed标签 阻止点击事件 让父元素处理点击事件
  • 原文地址:https://www.cnblogs.com/x54256/p/9429815.html
Copyright © 2011-2022 走看看