lundi 24 octobre 2016

Retrive private class member name

I am designing a Hibernate's entity Pre-Update Event Listener with Java 8.

I've created a StateTracker class that, from the PreUpdateEvent, gets the entity's new and old states and the parameters name. This class maps the parameters names to the corresponding pair of old and new states and a lazy evaluated Boolean hasChanged and make querying the map by key (which is of type String) available through a public method.

Problem is: I need to check if a specific property from an entity A, say it is named var, will have it's state changed by the update event. Naturally this can be done like this:

void foo(PreUpdateEvent event) {
    StateTracker stateTracker(event);
    if(stateTracker.isPropertyModified("var") {
        /* do stuff... */
    }
}

I know I can't always save the world, but if someone ever changes var name to catastrophe in A, then the above code will be broken, because even the smarter of the refactoring tools won't see that the String "var" is meant to represent the name of the parameter var (now catastrophe).

I am accepting that there is no better way out of this situation, but I want to be sure that is no way to get a variable name through reflection or something.

Ideally, this would work like this:

void foo(PreUpdateEvent event) {
    StateTracker stateTracker(event);
    if(stateTracker.isPropertyModified(A.class.var.getName()) { // Magic!
        /* do stuff... */
    }
}

Maybe some wizardry in the field of annotation processing could perform such magic...





Aucun commentaire:

Enregistrer un commentaire