In Java you can write:
System.out.println(Abc.class.getName());
It will always print the correct value, even if the class Abc is moved or renamed.
What is the closest you can get to that for field names?
In other words, what can I code that will always give me the "current" name of a field in a class, even if that field is renamed. Ideally, it would also fail to compile if the field is removed altogether. Or at least fail as soon as the class is accessed, during static initialisation.
I want this to simplify a "change tracking" system. It's not quite like "bean properties", because those names are NOT visible outside the class itself.
AFAIK, there is no "native" way to do this, but I'm hoping there might be some trick with annotations and/or reflection that does the job.
I'll write what I'm doing now (minimally simplified):
private static final String IS_SWAPPABLE = "isSwappable";
// ...
private boolean isSwappable;
// ...
public boolean isSwappable() {
if ((clientChanges != null) &&
clientChanges.containsKey(IS_SWAPPABLE)) {
return (Boolean) clientChanges.get(IS_SWAPPABLE);
}
return isSwappable;
}
public boolean setSwappable(final boolean newSwappable) {
if (isSwappable() != newSwappable) {
isSwappable = newSwappable;
onFieldChange(IS_SWAPPABLE, newSwappable);
return true;
}
return false;
}
What I would like is some "magic" that sets the value of IS_SWAPPABLE to "isSwappable" such that if isSwappable is renamed, then IS_SWAPPABLE will be updated appropriately.
OTOH, if there was a syntax like Abc.isSwappable (or Abc#isSwappable) or whatever, I would spare myself the constant, and just write that directly.
What I can do atm is (once) go over the constants (by using some clear naming convention), and make sure for each of them there is an instance field with the same name. But it doesn't really guaranties that IS_SWAPPABLE is used where isSwappable is used.