简体   繁体   中英

Retrieve 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...

是的,只需进行简单的反射,遍历选项卡,创建哈希集键(即字段名称,值是field的值),然后每次遍历您的集合并且如果任何项目状态已更改/移除,则将该实体标记为已更新

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM