简体   繁体   中英

Parse string based on type

I've seen some answer that are close to what Im looking for but they dont work.

So i have a lot of settings of different types and was wondering if I could parse the string value of them in 2 lines of code instead of doing it seperate for each. The settings look like this

    public static Setting<Boolean> e = new BooleanSetting("name",true);
    public static Setting<Integer> num = new IntegerSetting("number",1);

To parse it right now I check for the type, so for boolean and int it would look like

if(setting instanceof BooleanSetting) {
    setting.value=Boolean.parseBoolean(astring[1]);
}
if(setting instanceof IntegerSetting) {
    setting.value=Integer.parseInt(astring[1]);
}

But since I know the type of setting it is, is there any way I can do something like

setting.value=setting.type.parseType(astring[1])

I don't understand why and where you check the instanceof stuff.

BooleanSetting and IntegerSetting are implementations or subclasses of Setting<T> . They know what their T is.

Setting should have an abstract T parseValue(String s) in which every subclass or implementation decides how to parse that String .

For instance:

class BooleanSetting extends Setting<Boolean> { //or implements
  @Override
  Boolean parseValue(String s) {
    return Boolean.parseBoolean(s);
  }
}

This moves all type-specific parsing to the subclass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM