通过自定义注解标记类中属性的功能

需求:

接收一个消息类,
类的属性中有一个不确定属性名的属性表示消息类型
类的属性中有一个不确定属性名的属性表示消息内容

通过注解对属性进行标记;

注解

@Target(ElementType.FIELD) // 设置为使用在字段上
@Retention(RetentionPolicy.RUNTIME) // 运行时起效
@Documented 
public @interface MyMessage {
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyType {
}

消息类

public class Message1 {
    @MyType
    private String cType;
    @MyMessage
    private String message;
}

public class Message2 {
    @MyType
    private String type;
    @MyMessage
    private String msg;
}

执行方法

public class Main {

    public static void main(String[] args) {
        Message1 message1 = new Message1();
        message1.setCType("2");
        message1.setMessage("messsage");
        getMsg(message1);
    }

    /**
     * 获取消息
     * @param o 消息内容
     */
    public static void getMsg(Object o) {

        Class<?> aClass = o.getClass();
        Field[] fields = aClass.getDeclaredFields();
        Arrays.stream(fields)
                .forEach(f -> {
                    Annotation[] declaredAnnotations = f.getDeclaredAnnotations(); // 获取所有字段下所有注解
                    for (Annotation annotation : declaredAnnotations) {
                        if (annotation instanceof MyType)
                            get(o,f,"类型:");
                        if (annotation instanceof MyMessage)
                            get(o,f,"消息:");
                    }
                });
    }

    /**
     * 提取成员属性
     * @param o 消息类
     * @param f 属性
     * @param str 需要打印的字段
     */
    public static void get(Object o, Field f, String str) {
        try {
            String methodName = "get" + StrUtil.upperFirst(f.getName());
            Method method = o.getClass().getMethod(methodName);
            Object invoke = method.invoke(o);
            System.out.println(str + invoke);

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值