public class TestData {
public static final String DATA = "A"; // I change this to read DATA = "B"
}
public class MyTest extends UnitTest {
private MyClass myClass;
public void setUp() {
myClass = new MyClass(TestData.DATA); // After change, DATA has value "B"
}
}
public class MyClass {
private String myVar;
public MyClass(String myVar) { // After change, myVar still has value "A"
this.myVar = myVar;
}
}
- Change
TestData.DATAtoBby editing the source code in Eclipse - Restart server
- Run
MyTest MyClassstill receivesAwhen referencingTestData.DATA- ???
Things I tried: restart server, eclipsify project, clean project, restart eclipse, restart computer, refresh every file manually. I found this to work:
String data = TestData.DATA;
myClass = new MyClass(data);
Why can’t I pass DATA directly to MyClass constructor?
I’ve got no error messages, when I break at setUp, DATA has the value “B” since I’ve changed it, but when I step into MyClass myVar has the value “A”
You can’t change a
finalvariable. That’s what makes itfinal. But there is nothing wrong with passing thefinalvariable to a function. In fact, the sample code that you posted runs just fine.In your list of steps, you said ‘change DATA to “B”‘ though your code doesn’t show this step. But that’s fine, since that step wouldn’t compile.
If you need to alter a
finalvariable before passing it to a function, you need to make a local copy and change that copy instead.Update: Now that the question has been clarified, here are some more thoughts:
It sounds like something isn’t being recompiled properly. Perhaps you are running from an old version of the classes (i.e. you need to copy it somewhere)?
Also, you should know that although you may change the
TestDataclass, becauseDATAis declaredstatic final, Java may have inlined that constant into theMyTestclass (since it is guaranteed to never change) so you need to make sure thatMyTestis also recompiled.If you want to verify that you are using the latest version of a class, put some very “loud” code in a place where you know it should execute. For example, a
System.out.printlnor even throw aRuntimeException(sure, your program will fail, but if it doesn’t fail then you know that something isn’t being recompiled properly which will help you diagnose what is wrong).