Issue
i have this class with this static field
public class Parameters {
public Parameters()
{
}
public static Image img = new Image(new File("myImage.png").toURI().toString());
}
and the junit class
import Parameters.*;
@Test
void test() {
Image img = Parameters.img; //error here
}
the problem is that when i debug Parameters.img is null, i get the error java.lang.ExceptionInInitializerError, i don't know how to fix it, to read that image from the test
also to mention the Image class is from javafx.
Solution
That code style is not a good idea.
Your Parameters class includes static initialization - anytime any code so much as looks in the general direction of Parameters, the JVM realizes that Parameters hasn't been loaded yet, so the JVM goes out and loads it; as part of that job, the code new Image(new File("myImage.png").toURI().toString())
runs, and that throws an exception.
Exceptions in initializers are annoying for a number of reasons, thus leading to the conclusion: Do not put code that is somewhat likely to error in initializers.
A better strategy would be to make a method instead:
private static Image getMyImage() {
return new Image(...);
}
or possibly involve a cache of some sort (first time load it, future times just return the cached object). Now the exception is thrown 'during normal program flow' (as part of invoking a method, not as part of loading a class).
More generally, this concept doesn't work with File at all, you don't want images as separate files, they are resources and should be in the same place your class files are, even (especially!) if your class files are in a jar file. That involves: new Image(Parameters.class.getResource("myImage.png"))
. This tells the JVM to look in the same place Parameters.class is at.
This code should still be in a method and not in a static field init like this.
Answered By - rzwitserloot