簡體   English   中英

我應該避免使用注釋嗎?

[英]Should I avoid using annotations?

在我的項目中,我正在從 json 文件(使用 gson)加載配置,您可能知道,缺少的字段將用空字符串填充。

有些字段是強制性的,其他的必須大於 X,我想驗證它。

簡單(且丑陋)的方法是對每個屬性使用 if 條件,例如:

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

但是,我有不止一個字段,並且將來會添加越來越多的屬性,因此我構建了兩個注釋,稱為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;
}

當我對拼貼畫進行代碼審查時,他非常害怕注釋的使用,“這是非常冒險且非常昂貴的成本”..

我很高興知道你的想法,我應該為每個字段使用一個簡單的 if 嗎? 繼續反思? 或者我應該使用其他方式驗證字段?

注意:不使用 Spring / Hibernate。

首先,您正在嘗試重新發明輪子。 有一個名為Hibernate Validator的項目,它是 bean 驗證參考規范的實現。

以下是他們登陸頁面的示例:

public class Car {

   @NotNull
   private String manufacturer;

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

   @Min(2)
   private int seatCount;

   // ...
}

因此,您定義驗證並運行引擎,它將執行所有檢查並返回錯誤(如果有)。 您甚至可以推出自己的驗證,使其可擴展。

附注 - 這個項目與 Hibernate (在 java 世界 ORM 映射工具中眾所周知)沒有任何共同之處。

如果您需要類似的東西,該項目還與 spring MVC 集成。

無論如何,它確實使用了注釋方法,並且確實有一些性能損失。 然而這一切都取決於你有什么樣的數據,例如它仍然比網絡調用快得多,所以如果你的項目做這樣的事情,額外的成本可能可以忽略不計。

反射並不像以前在第一個 Java 版本中那么慢,但最重要的是,您應該嘗試看看它是否符合您的需求。 否則我只能推測。

Here你可以找到關於這個主題的教程,應該是相關的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM