How to convert comma delimited string to list T in core Java

"first time for a long time," as they say on radio talk shows ...

I am trying to parse a delimited property into a list. Simple enough, but for some reason I can't figure out how to do it in general using only Core Java. In general, what I mean is that the type of list to create can be List <String>, List <Integer>, or List <Double>. My final hit on it below gives runtime exceptions with non-Strings, because I am trying to use from String eg. Double, which is not allowed. Any help is appreciated.

public static <T> void parsePropsToList(String propName, String delim, List<T> listToFill){
   //This is paired down for convenience - assume getSplitList correctly parses to List<String>
   List<String> stringList = PropsManager.getSplitList(propName, delim);
   for(String s : stringList){
       listToFill.add((T)s);
   }
}

      

+2


a source to share


2 answers


You need to pass the class to your function, for example:

public static <T> void parsePropsToList(
  String propName,
  String delim,
  List<T> listToFill,
  Class<T> clazz)

      



then using clazz reflection , get a Constructor having one String for its argument, split propName by delim, and for each substring, call a new instance of T using the previous constructor. put this new instance in listToFill and return this list then.

+1


a source


Since Java gives out generic type information at runtime, you need to pass something to your method, which will allow you to convert from a property string to the correct type.

I think the easiest would be to add a Parser parameter to your method:



public interface Parser<T> {
  public T parse(String value);
}

static <T> void parsePropsToList(String propName, String delim, List<T> listToFill, Parser<T> parser) {
  String value;
  //extract value from property
  listToFill.add(parser.parse(value));
}

      

+1


a source







All Articles