0
public class SomeHelper {
    ...
    private int static x;
    static {
        Map<String, String> aMap = new HashMap<>();
        //populate map here
    }
    public static void setX(int value){
       x = value;
    }
}

When SomeHelper.setX is called, I get a "Could not initialize class SomeHelper" exception. I'm not sure how to fix this. Anyone faced this issue? I tried catching the exception and re throwing it as a runtime exception from the static block, but that doesn't help.

2 Answers2

1

I think you mean you get a NoClassDefFoundError like this:

NoClassDefFoundError: Could not initialize class SomeHelper

As JavaSE-7 states:

NoClassDefFoundError thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Sometimes NoClassDefFoundError occurs if the static bits of your class i.e. any initialization that takes place during the defining of the class, fails.

So first change

private int static x; 

to,

private static int x;

Declare setX() as static, or create instance of SomeHelper to invoke setX().

To invoke any method with the class name, the method should be static.

Try this:

public static void setX(int value){
   x = value;
}

SomeHelper.setX(someInteger);

Or this:

SomeHelper someHelper = new SomeHelper (); // default constructor 
someHelper .setX(someInteger);

Note that, You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

Community
  • 1
  • 1
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
  • Sorry, that method is already static. I'm not sure if the exception thrown is a NoClassDefFound error. I don't see the complete exception just the message "Could not initialize class SomeHelper". And I'm using JavaSE-8 – user3453363 Jul 14 '15 at 16:11
0

i) Make the method static to call it with className.

ii) Class not initialized indicates that initialization did not occur properly which might be due to an exception in static block.

iii) I see that your Map<String, String> aMap is local to static block. Aren't you using it anywhere else?

Ouney
  • 1,164
  • 1
  • 10
  • 22