Java自定义注解标签

自定义标签

在刚开始接触Java语言可能对标签的理解不是很好,但是进入JavaEE以及框架之后明显感觉注解标签可以省去很多事,比配置文件要容易很多。在Servlet概述中我有描述过简单得通过注解对Servlet类进行配置。

package com.wenhua.annocation;

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

/**
 * 自定义注解@NotNull
 */
@Target(ElementType.FIELD)// 作用范围
@Retention(RetentionPolicy.RUNTIME)// 保存时间(运行时期)
public @interface NotNull {
    // 定义标签的属性
    String message() default "";
}

自定义标签测试类

package com.wenhua.annocation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * User自定义标签测试类
 */
public class User {

    // 带有标签的私有属性
    @NotNull(message = "不能为空")
    private String name;

    // 公共set,get方法
    public String getName() {
        return name;
    }

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

    // main方法测试
    public static void main(String[] args) throws NoSuchMethodException,SecurityException, Exception {

        // 实例化对象
        User user = new User();
        user.setName("jim");// 给user类属性set值

        // 通过反射获取user类的所有属性
        Field[] fields = user.getClass().getDeclaredFields();

        // for循环遍历所有的属性
        for(Field field : fields){
            // 获得该属性上的注解标签
            NotNull notNull = field.getAnnotation(NotNull.class);
            if (notNull!=null){
                // 动态获取get方法名
                Method method = user.getClass().getMethod("get"+getMethodName(field.getName()));
                // 执行get方法,得到属性返回值
                Object obj = method.invoke(user);
                if(obj==null){
                    // 在控制台打印标签内容
                    System.out.println(field.getName()+notNull.message());
                    // 抛出异常
                    throw new NullPointerException(field.getName()+notNull.message());
                }else{
                    System.out.println("该属性的值为:"+obj);
                }
            }
        }

    }

    /**
     * 转化为首字母大写
     * @param name
     * @return
     */
    private static String getMethodName(String name) {
        byte[] names = name.getBytes();
        names[0] = (byte) ((char)names[0]-'a'+'A');
        return new String(names);
    }
}

测试结果

该属性的值为jim
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值