mercredi 25 novembre 2020

Invoking beans in java using alias/real names as input from a flat file/map

I need to invoke and instantiate n number of bean classes and their variables based on the input from a flat file or map.

I tried below using reflection but this helps only instantiating String type of variables and not generic. Please suggest. Can I use any existing API or something else to deal with this case study ?

public class PersonInstantiator {

  public static void main(String[] args) throws Exception{
    HashMap<String, String> objHashMap = new HashMap<String, String>();
    objHashMap.put("KEY1", "KEY1 VALUE");
    objHashMap.put("KEY2", "KEY2 VALUE");

    Object object = null;
    Class<?> objClass = null;

    Properties properties = new Properties();
    properties.load(PersonInstantiator.class.getResourceAsStream("MappingFile.txt"));

    for (Map.Entry<String, String> entry : objHashMap.entrySet()) {
        String input[] = properties.getProperty(entry.getKey()).split("-");
        String className = input[0];
        String methodName = input[1];

        objClass = Class.forName(className);
        if (null == object) {
            object = objClass.newInstance();
        }
        Class<?>[] cArg = new Class[1];
        cArg[0] = String.class;
        Method method = objClass.getDeclaredMethod("set" + methodName, cArg);
        method.setAccessible(true);
        method.invoke(object, entry.getValue());

    }

    System.out.println(object);
   }

Class person looks like below:

public class Person {

private String name;

private String city;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
@Override
public String toString() {
    return "Person [name=" + name + ", city=" + city + "]";
}

 }

Mapping file used is having below text.

 KEY1 = Person-Name
 KEY2 = Person-City




Aucun commentaire:

Enregistrer un commentaire