加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在编译时检查传递给method的字符串参数是否有@deprecate

发布时间:2020-12-15 02:26:22 所属栏目:Java 来源:网络整理
导读:我想验证传递给方法的字符串是否已弃用.例如.: 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,
我想验证传递给方法的字符串是否已弃用.例如.:

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
    }
    // ...
}

在这种情况下,你真的通过了这个领域,而不是它的价值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读