有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Google GSON:如何使用@Since注释,例如版本“1.2.1”?(无效双精度)

我正在Java应用程序中使用Google GSON

设想以下情况:在版本1.2.1中添加了一个新的JSON属性。我如何在^{}注释中使用它?显然,@Since(1.2.1)是不可能的,因为1.2.1不是有效的双精度。我的版本格式是<major>.<minor>.<patch>

我注意到的另一件事是,如果我有版本1.20,GSON将其视为比例如版本1.3更低的版本

有什么办法解决这个问题吗?也许可以做一些像定制排他性的工作?(这是否存在?)

除了版本问题之外,我注意到^{}注释也可以用于类。我找不到关于这个的任何文档。如果有人能解释为什么这是有用的,我将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    看起来@Since注释有点有限,不适合您。您需要自定义排除策略是正确的。下面这样的方法会奏效:

    1. 为要使用的版本创建自己的注释,而不是@Since

      @Retention(RetentionPolicy.RUNTIME)
      @Target({ElementType.FIELD, ElementType.TYPE})
      @interface VersionAnnotation {
          String versionNumber();
      }
      
    2. 自定义排除策略:

      class VersionExclusionStrategy implements ExclusionStrategy {
      
          private String versionNumber;
      
          VersionExclusionStrategy(String versionNumber) {
              this.versionNumber = versionNumber;
          }
      
          @Override
          public boolean shouldSkipClass(Class<?> classType) {
              VersionAnnotation va = classType.getAnnotation(VersionAnnotation.class);
      
              return va != null && versionCompare(this.versionNumber, va.versionNumber()) < 0;
          }
      
          @Override
          public boolean shouldSkipField(FieldAttributes fieldAttributes) {
              VersionAnnotation va = fieldAttributes.getAnnotation(VersionAnnotation.class);
      
              return va != null && versionCompare(this.versionNumber, va.versionNumber()) < 0;
          }
      
          private static int versionCompare(String str1, String str2) {
              // TODO implement
          }
      }
      
    3. versionCompare方法是比较版本字符串的方法。我使用了这个问题答案中的一个:How do you compare two version Strings in Java?

    4. 用法:

      Gson gson = new GsonBuilder().setExclusionStrategies(new VersionExclusionStrategy("1.3")).create();
      

    我不确定这对课堂有什么用处。可以对类进行注释,这样就不必对其他类中的所有类引用进行注释,但仅此而已