我是一名Java新手,已经进行了几天的基础编码。今天在处理变量和内部类时,我在使用内部类中的非最终变量时遇到了困难。
我正在使用testNG框架进行工作,这是我正在尝试的场景:
我正在使用testNG框架进行工作,这是我正在尝试的场景:
public class Dummy extends TestNG {
@Override
public void setUp() throws Exception {
log.error("Setup Goes here");
}
@Override
public void test() throws Exception {
String someString = null;
try {
someString = "This is some string";
} catch (Exception e) {
log.error(e.getMessage());
}
Thread executeCommand = new Thread(new Runnable() {
@Override
public void run() {
try {
runComeCommand(someString, false); <=====ERROR LINE
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
}
@Override
public void cleanUp() throws Exception {
}
}
当我编写上述代码时,它抛出一个错误,显示“无法引用内部类中的非最终变量”。因此,我实现了Eclipse提供的建议之一,即在父类中声明someString变量。现在代码如下所示:
public class Dummy extends TestNG {
String someString = null; <=====Moved this variable from test() to here
@Override
public void setUp() throws Exception {
log.error("Setup Goes here");
}
@Override
public void test() throws Exception {
<same code goes here>
}
@Override
public void cleanUp() throws Exception {
}
}
现在在eclipse中不显示任何错误。 我想知道为什么它现在可以接受内部类中的变量,即使变量不是final的。难道不应该出现相同的错误吗?现在这样会起作用吗?任何帮助都将是有益的。