Search code examples
javaeclipsepojo

Eclipse, Java: Generate class field from static string or vice versa


I am working on a JAVA web service with mongo, In order to implement mongo java driver POJO api (like Morphia), I establish my POJO like the following:

    public class User {
        public static final String USER_NAME = "userName";
        private String userName;
        public User() {
        }
        // getter && setter //
    }

USER_NAME = "userName" is a reference for future use as a filed name. What I'm trying to achieve is that I could use a simple if to check if received data equals to the field name. For example :

    User user = new User();
    String receivedData = httpRequest.getParameter(User.USER_NAME);
    if (receivedData == null) {
        return null;
    } else {
        user.setUserName(receivedData);
        userCollection.insertOne(user);  
            // userCollection is MongoCollection<User>
        return Gson().toJson(user);
    }

I am looking for a eclipse function or plug in that could auto generate one of the declaration (USER_NAME = "userName" and private String userName) by the other and make sure the consistency of the code.

Of course, that would be appreciated if there's any suggestion for a better practice.

EDIT

Stephan's reflection approach gives a great flexibility for the code. However, compare to my original simplified example, the real situation might be more complex. For example, one httpRequest has many different parameters which are stored in different(n) POJO and each POJO has many different(n) fields. In that case, we will do n*n loop for just getting the field value.


Solution

  • If you want to do the same for all fields of the POJO, consider iterating the result of User.class.getFields(). For each Field get the name (f.getName()), use the name to retrieve the value and set it to the field (f.set(object,value)). With this approach there's no need for a constant like USER_NAME.

    EDIT 1: If performance is an issue you may of course collect all those fields into some collection up-front once and for all, but then the bottleneck will remain at having to try httpRequest.getParameter() for each possible field. Nothing specific to the reflective approach.

    EDIT 2: In a "nicer" language there could be type checked syntax for retrieving a Field instance, e.g., imagine (not Java):

    Field f = User::userName;
    

    This answer basically demonstrates that generating redundant constants is not strictly necessary, since the thing that consistently connects the name to the field already exists, it's a Field.