简体   繁体   English

我应该避免使用注释吗?

[英]Should I avoid using annotations?

In my project I'm loading configuration from a json file (using gson) and as you probably know, missing fields will be populate with an empty string.在我的项目中,我正在从 json 文件(使用 gson)加载配置,您可能知道,缺少的字段将用空字符串填充。

Some of the fields are mandatory and other must be greater then X, and I want to validate it.有些字段是强制性的,其他的必须大于 X,我想验证它。

The simple (and ugly) way is to use if condition for each property, like:简单(且丑陋)的方法是对每个属性使用 if 条件,例如:

if (StringUtils.isEmpty(sftpConfiguration.getHostName)) {
   logger.error (“hostName property is mandatory”);
  // etc.
}

but, I have more than one field and more and more properties will added in the future, therefore I built two annotations, called NorNullEmpty and GreaterThen (with value property) and I run throw the fields like this:但是,我有不止一个字段,并且将来会添加越来越多的属性,因此我构建了两个注释,称为NorNullEmptyGreaterThen (带有 value 属性),然后我运行 throw 像这样的字段:

public static boolean validateWithAnnotation(Object object) throws IllegalAccessException {
    boolean result = true;
    Field[] classFields = object.getClass().getDeclaredFields();

    for (Field field : classFields) {
        if (field.getAnnotation(NorNullEmpty.class) != null) {
            if (field.getType() == String.class) {
                field.setAccessible(true);
                String value = (String) field.get(object);
                if (StringUtils.isEmpty(value)) {
                    result = false;
                    logger.error("Property {} is mandatory but null or an empty.", field.getName());
                }
                field.setAccessible(false);
            } else {
                logger.warn("@NorNullEmpty annotation is working on String type only.");
            }
        } else if (field.getAnnotation(GreaterThan.class) != null) {
            Class<?> fieldType = field.getType();
            if (fieldType == long.class || fieldType == Long.class) {
                field.setAccessible(true);
                Long val = field.getLong(object);
                if (val <= field.getAnnotation(GreaterThan.class).value()) {
                    result = false;
                    logger.error("Property {} value is {} and it must be greater than {}.", field.getName(), val, field.getAnnotation(GreaterThan.class).value());
                }
                field.setAccessible(false);
            }
        }
    }

    return result;
}

When I did a code review with a collage he very afraid from the annotations use, “it's very risky and very expensive cost”..当我对拼贴画进行代码审查时,他非常害怕注释的使用,“这是非常冒险且非常昂贵的成本”..

I'll be glad to know what you think, should I use a simple-stupid if for each field?我很高兴知道你的想法,我应该为每个字段使用一个简单的 if 吗? continue with the reflection?继续反思? or I should validate the fields using other way?或者我应该使用其他方式验证字段?

Note: NOT using Spring / Hibernate.注意:不使用 Spring / Hibernate。

First of all you're trying to re-invent the wheel.首先,您正在尝试重新发明轮子。 There is a project called Hibernate Validator which is an implementation of the bean validation reference specification.有一个名为Hibernate Validator的项目,它是 bean 验证参考规范的实现。

Here is an example from their landing page:以下是他们登陆页面的示例:

public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}

So you define validations and run the engine, it will perform all the checks and return Errors if there are any.因此,您定义验证并运行引擎,它将执行所有检查并返回错误(如果有)。 You can even roll your own validations which makes it extensible.您甚至可以推出自己的验证,使其可扩展。

One side-note - this project has nothing common with Hibernate (a well known in the java world ORM mapping tool).附注 - 这个项目与 Hibernate (在 java 世界 ORM 映射工具中众所周知)没有任何共同之处。

This project also integrates with spring MVC if you need something like that.如果您需要类似的东西,该项目还与 spring MVC 集成。

Anyway, it does use the annotation approach and it indeed has some performance penalty.无论如何,它确实使用了注释方法,并且确实有一些性能损失。 However it all depends on what kind of data do you have, for example its still much faster than doing network calls, so if your project does something like that, probably the additional cost will be negligible.然而这一切都取决于你有什么样的数据,例如它仍然比网络调用快得多,所以如果你的项目做这样的事情,额外的成本可能可以忽略不计。

Reflection is not that slow as it used to be in the first Java versions, but bottom line you should try and see yourself whether it fits your needs.反射并不像以前在第一个 Java 版本中那么慢,但最重要的是,您应该尝试看看它是否符合您的需求。 Otherwise I can only speculate.否则我只能推测。

Here you can find a tutorial about this topic, should be relevant Here你可以找到关于这个主题的教程,应该是相关的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM