java - Generic way to convert String to Object -


i implementing utility method accept string parameter , convert object generic. can achieve code below weak point every object need parse must have string constructor. there no way of defining object must have string constructor. there other better way achieve using polymorphism or generic?

aaa.java

public class aaa {     private string id;     private string description;      public aaa(string str) {         // parsing...      } 

utility method.

public static <t extends base> list<t> readfile(file file, class<t> type) {     list<t> collection = new arraylist<t>();     // read file line line , convert instance      constructor<t> ctor = type.getconstructor(string.class);     t newinstance = ctor.newinstance(line);     if (newinstance != null) {         collection.add(newinstance);     }        return collection; } 

usage:

list<aaa> list = fileutil.readfile(file, aaa.class); 

i assume pojo classes (the 1 contain data) in format have in example. meaning fields string values. if not case solution needs little bit of refinement.

my suggestion use reflection use case describe. have been successful in past. although reflection can pose severe performance penalties if applied badly.

parsing code following. omit method header since 1 provide looks good. code provide assume in string[] variable line find parsed line of csv file. each element of array containing 1 column of csv line.

string[] line; // initialised explained above t newinstance = t.newinstance(); // invoke default constructor field[] fields = newinstance.getclass().getdeclaredfields(); // use reflection read fields int count = 0; for(fields f : fields) {     f.set(newinstance, line[count]);     count++; } 

disclaimer: above code not boundary checks! assumption csv lines , number of fields in class have same length!

on field objects call getannotation check whether or not annotation set on field. allows write classes that:

public class aaaannotated {      @mycsvannotation     string field1;      @mycsvannotation     string field2;      string field3; } 

if code checks whether or not fields annotated annotations can control in pojo classes fields load form csv , leave untouched.


Comments