lundi 21 août 2017

Java Switch-statement refactor txt to Class Set

How do i refactor like this code.

Origin source code is text file parsing to Class setter.

So i make Mokup String array and for loop...for your test

and recommend some Design-Pattern i have no idae Design-Patterns

Plz give some idea :)

Have a Nice day!

public class Parsing {
  static String[] arr = {"test: 1", "X: 2", "abc: 3", "def: 4", "jx: 5", "rx: 6"};

  public static class Vo {
    String test,x,abc,def,jx,rx;
    public void setTest(String test) {
      this.test = test;
    }
    public void setX(String x) {
      this.x = x;
    }
    public void setAbc(String abc) {
      this.abc = abc;
    }
    public void setDef(String def) {
      this.def = def;
    }
    public void setJx(String jx) {
      this.jx = jx;
    }
    public void setRx(String rx) {
      this.rx = rx;
    }
    @Override
    public String toString() {
      return "Vo [test=" + test + ", x=" + x + ", abc=" + abc + ", def=" + def + ", jx=" + jx
          + ", rx=" + rx + "]";
    }
  }

  public static void main(String[] args) {
    Vo vo = new Vo();
    for(String x : arr) {

      String[] arrKeyVal = x.split(" ");
      String key = arrKeyVal[0].replace(":","");
      String val = arrKeyVal[1];

      switch(key) {
        case "test": vo.setTest(val); break;
        case "X": vo.setX(val); break;
        case "abc": vo.setAbc(val); break;
        case "def": vo.setDef(val); break;
        case "jx": vo.setJx(val); break;
        case "rx": vo.setRx(val); break;
        /***
         * ......ex 20 case 
         */
        default: break;
      }
    }

    System.out.println(vo.toString());
  }
}

Aucun commentaire:

Enregistrer un commentaire