简化更新私有成员的切换表达式

问题描述 投票:0回答:2

我想简化这个逻辑:

  private String member_A;
  private String member_B;
  private String member_C;
  private String member_D;

 private void xyz(Object x, String s) {
 switch (s) {
    case "A":
      member_A = x.getInternalNumber();
      break;
    case "B":
      member_B = x.getInternalNumber();
      break;
    case "C":
      member_C = x.getInternalNumber();
      break;
    case "D":
      member_D = x.getInternalNumber();
      break;
    default:
    }
 }


 xyz(x, "A");
 ...
 xyz(x, "B");
 ...
 etc

switch将被更优雅的解决方案所取代。从技术上讲,xyz(...)的调用应使用某个值更新正确的字段。有没有人有想法改善这个?

java switch-statement mapping
2个回答
0
投票

如果您的成员变量的命名约定与示例代码中给出的一样,则可以使用反射。如果它比你现在的更优雅,那就值得商榷。

private void xyz(Object x, String s) {
    try {
        Field member = YourClass.class.getDeclaredField("member_"+s); //replace YourClass with your class name
        member.setAccessible(true);
        member.set(this, x.getInternalNumber());
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ex) {

    }
}

0
投票

你可以成为一个class会员。也许是这样的:

class Member {

    String string;
    char member;

    Member (char member) {
        this.string = null;
        this.member = member;
    }
}

然后制作一个成员的array,然后在foreach循环中测试每个成员,如下所示:

private void test(char s) {
    for (Member m : members) {
        if (m.member == s) {
            m.string = "Whatever you want that member string to be equal to";
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.