mardi 24 janvier 2017

Java Extracting out Initializing private fields of a class

Is it possible to solve the following problem using inbuilt Java API? (I want to retain the strict private access as shown)

  1. I have n subclasses of an abstract class BaseModel.
  2. Each of these subclasses declare their own set of private String fields.
  3. Within the subclass constructor, I wish to set the private fields from a Map using Java Reflection. An example of this function:

    void setPrivateFields(Map<String, String> fieldsValuesMap) throws NoSuchFieldException, IllegalAccessException {
        for (Map.Entry<String, String> entry : fieldsValuesMap.entrySet()) {
            String fieldName = entry.getKey();
            String fieldValue = entry.getValue();
    
            Field field = this.getClass().getDeclaredField(fieldName);
            field.set(this, fieldValue);
        }
    }
    
    
  4. Is it possible to extract out the function I have described in 3) such that I do not have to rewrite the algorithm in all the constructors of the subclasses?

    class BaseModel {}
    
    class Project extends BaseModel {
        private String name;
        private String type;
    
        public Project(Map<String, String> fieldsValuesMap) {
            setPrivateFields(fieldsValuesMap);
        }
    }
    
    class Task extends BaseModel {
        private String description;
        private String rawDescription;
    
        public Task(Map<String, String> fieldsValuesMap) {
            setPrivateFields(fieldsValuesMap);
        }
    }
    
    class SubTask extends BaseModel {
      ...   
    }
    
    ...
    
    

Aucun commentaire:

Enregistrer un commentaire