开发者

How to convert comma delimited String to List of T in Core Java

开发者 https://www.devze.com 2022-12-28 13:29 出处:网络
\"first time long time\" as they say on the radio talk shows... I\'m trying to parse a delimited property into a List.Simple enough, but for some reason I can\'t figure how to do this in a generic fa

"first time long time" as they say on the radio talk shows...

I'm trying to parse a delimited property into a List. Simple enough, but for some reason I can't figure how to do this in a generic fashion using only Core Java. By generic, I mean the type of List to create may be a List< String >, List< Integer >, or List< Double >. My latest stab at it below give开发者_高级运维s runtime exceptions with non-Strings because I'm trying to cast from String to e.g. 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);
   }
}


You need to pass the Class in your function, something like;

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

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


Since Java throws out generic type information at runtime, you need to pass something in to your method that'll let you convert from the property string to the correct type.

I think the easiest thing to do 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));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号