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

查看:122
本文介绍了如何在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.

For实例:我将把 @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 类,它将使用反射来检查方法是否有注释并执行某些工作,例如说如果 oldValue newValue 相等:

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;
    }
}

干杯,
Michal

Cheers, Michal

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

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