【问题标题】:Reset or Clear Static Variable重置或清除静态变量
【发布时间】:2018-09-18 09:38:19
【问题描述】:

我正在探索另一个线程中给出的答案: Can you reset a static variable? 但我的查询略有不同:

static int counter = 1;
public void captureField(String fieldValue, String type) throws Throwable {
    String value = "Hello";
    writeFieldValue(value, type, counter++);
}

public static void writeFieldValue(String fieldValue, String type, int counter) throws IOException {
    *//File Handling code here*
    sheet.getRow(counter).getCell(5).setCellValue(fieldValue);
}

上面的代码在第一种情况下正常工作,其中计数器正确递增以按顺序在单元格中添加 fieldValue。但是,要执行下一个场景,计数器值应重置为 1。

问题是:

'counter'值在针对特定场景执行后不会重置为1并抛出java.lang.NullPointerException。

【问题讨论】:

    标签: variables static


    【解决方案1】:

    我已经找到了解决方案。添加了另一个静态变量“txnTypex”,它将继续检查类型值,每当值更改时,计数器将重置为 1。

    static int counter = 1;
    static String txnTypex = "";
    public void captureField(String fieldValue, String type) throws Throwable {
         String value = "Hello";
         if(!txnTypex.equals(txnType))
            counter=1;
    
         writeFieldValue(value, type, counter++);
         txnTypex=txnType;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2014-12-26
      相关资源
      最近更新 更多