如何在java中创建自定义注释? [英] How to create custom annotation in java?

查看:46
本文介绍了如何在java中创建自定义注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 java 中为 DirtyChecking 创建自定义注释.就像我想使用此注释比较两个字符串值,比较后它将返回一个 boolean 值.

I want to create custom annotation in java for DirtyChecking. Like I want to compare two string values using this annotation and after comparing it will return a boolean value.

例如:我会将 @DirtyCheck("newValue","oldValue") 放在属性上.

For instance: I will put @DirtyCheck("newValue","oldValue") over properties.

假设我做了一个接口:

 public @interface DirtyCheck {
    String newValue();
    String oldValue();
 }

我的问题是:

  1. 在哪里创建一个类来创建用于比较两个字符串值的方法?我的意思是,这个注解如何通知我必须调用这个方法?
  2. 如何检索此方法的返回值?

推荐答案

首先需要标记注解是针对类、字段还是方法.假设它是用于方法的:所以你在你的注释定义中写下这个:

First you need to mark if annotation is for class, field or method. Let's say it is for method: so you write this in your annotation definition:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DirtyCheck {
    String newValue();
    String oldValue();
}

接下来你必须编写比方说 DirtyChecker 类,它将使用反射来检查方法是否有注释并做一些工作,例如如果 oldValuenewValue 是相等的:

Next you have to write let's say DirtyChecker class which will use reflection to check if method has annotation and do some job for example say if oldValue and newValue are equal:

final class DirtyChecker {

    public boolean process(Object instance) {
        Class<?> clazz = instance.getClass();
        for (Method m : clazz.getDeclaredMethods()) {
            if (m.isAnnotationPresent(DirtyCheck.class)) {
                DirtyCheck annotation = m.getAnnotation(DirtyCheck.class);
                String newVal = annotation.newValue();
                String oldVal = annotation.oldValue();
                return newVal.equals(oldVal);
            }
        }
        return false;
    }
}

干杯,迈克尔

这篇关于如何在java中创建自定义注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆