有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java设置类字段,然后在方法中修改它们

我不经常写java,当我写java时,通常会扩展其他代码,所以我为这个问题的基本性质道歉。我有一个用来测试另一个应用程序的类。这个类中的每个方法都是一个单独的测试。这门课上有数百个测试。随着这个类的发展,每一个新方法都被克隆,因此在总体设计中没有太多的远见。我正试图重构这个类,使它更易于维护

对于这个问题,每个方法都有一块填充2个字符串数组的代码。数组1是要打开的内容的列表。数组2是一个你想要的东西的列表。这两个数组作为parms传递到另一个方法中。问题是,如果你创建了一个新的“你想要开/关的东西”,你必须在每个方法中设置它。我想将array1和array2移动到属性。请参见下面的代码示例

Public class MyClass{
   String[] OnThings = {"Thing1", "Thing2"}
   String[] OffThings = {"Thing3"}
}

protected void Test1{
   /**Below method iterates both arrays and turns things on or off**/
   turnThingsOnOrOff(OnThings, OffThings)
   /**Do a bunch of testing here**/
}

protected void Test2{
   /**This particular test I want to turn off Thing 1**/
   OnThings.Remove{"Thing1"}
   OffThings.Add{"Thing1"}
   turnThingsOnOfOff(OnThings, OffThings)
   /**Do a bunch of testing here**/
}

由于代码当前存在,如果你想添加一个新东西(Thing4)并在每次测试中测试它,你必须进入100个方法中的每一个,并将其添加到“OnThings”列表中

使用建议的代码,只需将Thing4添加到class属性中一次,它将在所有测试中运行。如果要在一些测试中禁用If,则可以使用修改这些方法。添加和。移除

目前,字符串数组似乎不支持添加或删除


共 (1) 个答案

  1. # 1 楼答案

    创建onThingsoffThings属性static,这样您就可以在类外使用它们,而无需每次创建new对象

    另外,如果要从数组中添加或删除数据,请使用ArrayList<String>而不是String[]ArrayLists的大小是动态的,可以很容易地添加或删除对象

    以下是修改后的代码:-

    Public class MyClass{
       public static ArrayList<String> OnThings = new ArrayList<String>(Arrays.asList("Thing1", "Thing2"));
       public static ArrayList<String> OffThings = new ArrayList<String>(Arrays.asList("Thing3"));
    }
    
    protected void Test1{
       /**Below method iterates both arrays and turns things on or off**/
       turnThingsOnOrOff(MyClass.OnThings, MyClass.OffThings)
       /**Do a bunch of testing here**/
    }
    
    protected void Test2{
       /**This particular test I want to turn off Thing 1**/
       OnThings.Remove{"Thing1"}
       OffThings.Add{"Thing1"}
       turnThingsOnOfOff(MyClass.OnThings, MyClass.OffThings)
       /**Do a bunch of testing here**/
    }
    

    有关ArrayList的更多信息,请参见here