我正在使用Google GSON在我的 Java 应用程序中。
想象一下以下情况:在版本 1.2.1
中添加了新的 JSON 属性。我如何在 @Since
中使用它注解?显然,@Since(1.2.1)
不可能,因为 1.2.1
不是有效的 double 。我的版本格式是<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();
我不确定这对类(class)有什么用处。您可以对类进行注释,这样就不必对其他类中的所有类引用进行注释,仅此而已。
关于java - 谷歌 GSON : How to use @Since annotation for e. g。版本 "1.2.1"? (无效双),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45175993/