我想验证传递给方法的字符串是否已弃用。例如:
public class MyRepo
@Deprecated
private static final String OLD_PATH = "old_path";
private static final String NEW_PATH = "new_path";
//...
public load(Node node){
migrateProperty(node, OLD_PATH , NEW_PATH );
//load the properties
loadProperty(node, NEW_PATH);
}
//I want to validate that the String oldPath has the @Deprecated annotation
public void migrateProperty(Node node, String oldPath, String newPath) {
if(node.hasProperty(oldPath)){
Property property = node.getProperty(oldPath);
node.setProperty(newPath, (Value) property);
property.remove();
}
}
//I want to validate that the String path does not have the @Deprecated annotation
public void loadProperty(Node node, String path) {
//load the property from the node
}
}
我能找到的最近的是 validating annotations on the parameters themselves .
最佳答案
您的注释将字段 OLD_PATH
标记为已弃用,而不是字符串 "old_path"
。在对 migrateProperty
的调用中,您传递的是字符串,而不是字段。因此该方法不知道值来自哪个字段,也无法检查它是否有注释。
通过注释,您可以声明有关 Java 元素的一些信息,例如类、字段、变量、方法。您不能注释对象,例如字符串。
您链接到的文章讨论了注释形式参数。同样,注释的是参数,而不是参数(传递的值)。如果将 @Something 放在方法参数上,则此参数将始终独立于此方法的调用者传递的值进行注释。
您可以做什么 - 但我不确定这是否是您想要的 - 如下:
@Deprecated
private static final String OLD_PATH = "old_path";
private static final String NEW_PATH = "new_path";
public load(Node node){
migrateProperty(node,
getClass().getDeclaredField("OLD_PATH"),
getClass().getDeclaredField("NEW_PATH") );
// ...
}
//I want to validate that the String oldPath has the @Deprecated annotation
public void migrateProperty(Node node, Field<String> oldPath, Field<String> newPath) {
if ( oldPath.getAnnotation(Deprecated.class) == null ) {
// ... invalid
}
// ...
}
在这种情况下,您真正传递的是该字段,而不是它的值。
关于java - 在编译时检查传递给方法的字符串参数是否有@deprecated 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6373887/