mardi 22 septembre 2015

How do I assign method name (or annotation element) strings in a way that is safe for refactoring?

Suppose I have a class com.example.Foo and another class com.sample.Bar which needs to know the fully-qualified name of Foo. If I am a Java novice I might put:

public class Bar {
    private String fooName = "com.example.Foo";
    //...
}

However, if I refactored Foo to change the name or package, the changes would not be reflected in Bar, unless the IDE is really clever. So it's better to do something like this:

import com.example.Foo;

public class Bar {
    private String fooName = Foo.class.getName();
    // ...
}

This way, if I refactor Foo, then the change should be picked up by Bar.

Now consider methods. If I have a method name in class Foo and the name needs to be known by Bar, it seems the best I can do is:

public class Bar {
    private String bazName = Foo.class.getMethod("bazMethod", Qux.class);
    // ...
}

But I haven't actually achieved anything - I still have a string literal "bazMethod" which won't be refactored if the real bazMethod gets renamed.

What I really want to do is something like:

public class Bar {
    private String bazName = tellMeTheMethodName((new Foo()).bazMethod(null));
    // ...
}

Not sure if this is possible somehow and if there is any way around it.

Now comes the real problem - even if you can sort that out as above, the real thing I am trying to access is an annotation attribute/element name. But annotations are abstract and cannot even be instantiated. So is this possible?





Aucun commentaire:

Enregistrer un commentaire