mercredi 9 mars 2016

How can I improve the design for this generic processor (parser)

I have a Json stream parser and I have the following piece of code that I use during parsing to populate relevant object:

public class CustomerParser implements GenericParser{  
    private static class ClazzArgs {  
        String methodName;  
        Class paramType;  
        public ClazzArgs(String methodName) {  
          this.methodName = methodName;  
        }  
       public ClazzArgs(String methodName, Class param) {   
           this.paramType = param;  
           this.methodName = methodName;   
       }  
    }  

private static final HashMap<String, ClazzArgs> mappings = new HashMap<>();   

static {   
  mappings.put(“customer_id”, new ClazzArgs("setCustomerId", Integer.TYPE));   
  mappings.put(“customer_name”, new ClazzArgs("setCustomerName", String.class));    
  mappings.put(“customer_address”, new ClazzArgs("setCustomerAddress");   
}    


private static void process(JsonReader reader, Customer customer, String tag) {   
    ClazzArgs params = mappings.get(tag);  
    try {  
       Method method = null;  
       Object inputArg = null;   
       if(params.paramType == null) {   
          inputArg = Utils.getParser(tag).parseToken(reader);   
          method = customer.getClass().getMethod(params.methodName, inputArg.getClass());  
  }  else {  
     String setter = params.methodName;  
     Class argType = params.paramType;  
     method = customer.getClass().getMethod(setter, argType);  
     inputArg = Utils.getDefaultParser(argType).parseToken(reader);  
  }  
  method.invoke(customer, inputArg);  
} catch(Exception e){} 

Can I improve the code design wise? (Exception handling omitted for clarity).
Also the idea is that there are many such type of Parsers e.g. ProductParser and it would be nice if I could make it more generic

Aucun commentaire:

Enregistrer un commentaire