简体   繁体   中英

How do I change the value of a variable based on another value in POJO?

I have the following POJO class:

@Value
@Builder
@RequiredArgsConstructor
public class XYZ {

    @NonNull
    private final String a;

    @NonNull
    private final Map<Integer, ABC> items;

    @NonNull
    private final State state;

    public enum State {
        STARTED,
    INPROGRESS,
        STOPPED
    }
}

Now, in this, based on different sizes of the map, I wanted to change the value of state field. Eg. When size is 0, then state should be STOPPED and when it is less than 5 and more than 0, then it is INPROGRESS and if it is more than 5, then it should be STARTED.

What is the best way to do this? Should this logic lie inside this POJO or should I explicitly check this whenever I am making change in map explicitly. How can I do it properly? Any ideas?

Possibly in a Constructor Take a Look at following

https://crunchify.com/create-simple-pojo-and-multiple-java-reflection-examples/

You can use manually defined getter

public State getState() {
    State newState = new State();
    // set newState based on map size
    return newState;
}

As you have defined state as final, don't try to assign values to it. Instead use a new variable newState;

Now whenever you call xYZ.getState(), you will get the updated value based on map size.

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