Java – check whether the string parameter passed to method has @ deprecated annotation at compile time

I want to verify that the string passed to the method is deprecated For example:

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

The closest I can find is validating annotations on the parameters

Solution

Your comment will the field old_ Path is marked deprecated instead of the string 'old_path' In the call to migrateproperty, you pass a string instead of a field Therefore, the method does not know the field from which the value comes and cannot check the comment

Using annotations, you can describe Java elements, such as classes, fields, variables, and methods You cannot annotate objects, such as strings

The article you linked discusses annotation form parameters Again, it is an annotated parameter, not a parameter (passed value) If you put @ something in a method parameter, the parameter will always be annotated independently of the value passed by the caller of the method

What you can do – but I'm not sure if this is what you want – is as follows:

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

In this case, you really passed the field, not its value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>