Google GSON:如何将@Since注释用于例如版本“1.2.1”? (invalid double)
问题描述:
我在我的Java应用程序中使用Google GSON。Google GSON:如何将@Since注释用于例如版本“1.2.1”? (invalid double)
想象一下以下情况:在版本1.2.1
中添加了新的JSON属性。我如何在@Since
注释中使用它?显然,@Since(1.2.1)
是不可能的,因为1.2.1
不是有效的双倍。我的版本格式是<major>.<minor>.<patch>
。
我注意到的另一件事,如果我有版本1.20
,GSON认为它比版本1.3
更低的版本。
任何想法如何解决这个问题?也许可能像自定义排除工具一样工作? (这是否存在?)
除了版本问题,我注意到@Since
注释也可以用于类。我找不到任何关于此的文档。如果有人能够解释为什么这很有用,我将不胜感激。
答
它看起来像@Since
注释有点有限,不适合你。您需要自定义排除策略是正确的。像下面的东西会工作:
-
创建自己的注释的版本,而不是使用
@Since
:@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) @interface VersionAnnotation { String versionNumber(); }
-
自定义排除策略:
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 } }
的
versionCompare
方法是什么会比较你的版本字符串。我用了一个从这个问题的答案:How do you compare two version Strings in Java?-
用法:
Gson gson = new GsonBuilder().setExclusionStrategies(new VersionExclusionStrategy("1.3")).create();
我不知道如何做到这一点的类是有用的。您可以注释该类,以便您不必注释其他类中的所有类引用,但这就是关于它的。
谢谢,我明白了。我已经意识到默认的'@ Since'注释不会起作用,它太有限了。一个类的注释实际上非常方便。如果在新的API版本中引入新的“功能”,我可以仅注释类而不是每个新字段。这种方式更具可读性。 –