重置或清除静态变量

时间:2018-09-18 09:38:19

标签: variables static

我正在探索另一个线程给出的答案: 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。

问题是:

针对特定情况执行后,“计数器”值未重置为1,并抛出java.lang.NullPointerException。

1 个答案:

答案 0 :(得分:0)

我有解决方案。添加了另一个静态变量“ 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;
}
相关问题