I get a java.lang.ExceptionInInitializerError but I don´t have a static initializer.
Code:
public static final File STANDARD_INDEX_FILE = new File(HTMLFileLoader.class.getClassLoader().getResource("index.html").getPath()); // Line 16
The HTMLFileLoader class is empty.
Exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
at net.guardian.Guardian.main(Guardian.java:12)
Caused by: java.lang.NullPointerException
at net.guardian.socket.MainSocket.<init>(MainSocket.java:16)
at net.guardian.socket.MainSocket.<clinit>(MainSocket.java:24)
... 1 more
This:
public static final File STANDARD_INDEX_FILE = new File(HTMLFileLoader.class.getClassLoader().getResource("index.html").getPath()); // Line 16
is exactly the same as this:
public static final File STANDARD_INDEX_FILE;
static {
STANDARD_INDEX_FILE = new File(HTMLFileLoader.class.getClassLoader().getResource("index.html").getPath()); // Line 16
}
As in, this is what it looks like in the compiled code.
As such, you do have a static initializer; and the exception is occuring somewhere in that initializer block.
Related
I have a cucumber and selenium test which has always worked fine and suddenly stops running with the below error.
1 Scenarios (1 failed)
14 Steps (14 skipped)
0m0.004s
java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.picocontainer.injectors.AbstractInjector.newInstance(AbstractInjector.java:145)
at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:342)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.NullPointerException
at com.optal.browsers.WebDriverFactory.createAndSetUpThreadedBrowser(WebDriverFactory.java:56)
at com.optal.browsers.WebDriverFactory.create(WebDriverFactory.java:37)
at com.optal.hooks.ScenarioHooks.<clinit>(ScenarioHooks.java:19)
... 24 more
java.lang.NoClassDefFoundError: Could not initialize class com.optal.hooks.ScenarioHooks
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.picocontainer.injectors.AbstractInjector.newInstance(AbstractInjector.java:145)
at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:342)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runAfterHooks(Runtime.java:206)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Calling System.exit() ..................
Process finished with exit code 1
ExceptionInInitializerError
An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.
The ExceptionInInitializerError is thrown when the JVM attempts to load a new class. During the class loading procedure, all static variables and static initializers are being evaluated. A static initializer is a block enclosed within curly braces without having any name and return type, except having the keyword static.
An example of a static initializer:
import java.util.UUID;
class Example {
private static String ID = null;
static {
ID = UUID.randomUUID().toString();
}
}
The static initializer is evaluated only once during the class loading procedure. Thus, a thrown exception in the evaluation of a static variable or initializer is wrapped into an ExceptionInInitializerError, in order for the JVM to indicate that the class could not be initialized and loaded.
An example that throws ExceptionInInitializerError error is as follows:
public class Example {
private static String message = null;
private static String subMessage = null;
public Example(String message) {
Example.message = message;
}
static {
/* Store the first 10 characters of the input message. */
subMessage = message.substring(0, 10);
}
public String getSubMessage() {
return subMessage;
}
public static void main(String[] args) {
Example exampleClass = new Example("Test");
System.out.println(exampleClass.getSubMessage());
}
}
Executing the above code snippet you will see the following error:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at main.java.Example.<clinit>(Example.java:13)
You can use either of the following methods to extract more information about the underlying actual exception:
getException(): Returns the exception that occurred during a static initialization that caused this error to be created.
getCause(): Returns the exception that caused this error to be thrown.
Dealing with ExceptionInInitializerError
The ExceptionInInitializerError is used as a wrapper to indicate that an exception arises in the static initializer block or the evaluation of a static variable’s value. Thus, we have to ensure that the original exception is fixed, in order for the JVM to be able to load our class successfully.
Outro
You can throw unchecked / runtime exceptions from the block of a static initializer. However, you cannot allow a checked exception to propagate out of a static block, because is not possible to handle these exceptions in your source.
if you are using Mac M1 chip and room lib , try this : In project-level build.gradle, add the following configuration in allprojects :
allprojects {
repositories {
// ...
}
// ADD THE FOLLOWING
configurations.all {
resolutionStrategy {
force 'org.xerial:sqlite-jdbc:3.34.0'
}
}
}
Ref : https://stackoverflow.com/a/70232822/7048025
I have a class named MyCollection in the directory
C:\Users\risha\OneDrive\RishavAgarwal\MyJavaClasses\utility\
inside the package - MyJavaClasses.utility
I have written a class named P22_Generics1 in the directory
C:\Users\risha\OneDrive\Documents\Java Practice\
This class uses the above created class.
I successfully compiled it using the command
javac P22_Generics1.java -cp C:\Users\risha\OneDrive\RishavAgarwal
Now, when I try to run it using the command java P22_Generics1, this error occurs
Exception in thread "main" java.lang.NoClassDefFoundError: MyJavaClasses/utility/MyCollection
at P22_Generics1.main(P22_Generics1.java:5)
Caused by: java.lang.ClassNotFoundException: Java.utils.Collection
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
What can I do to execute it successfully?
The P22_Generics1.java looks like this
import MyJavaClasses.utility.MyCollection;
public class P22_Generics1 {
public static void main(String[] args) {
MyCollection<Integer> collection = new MyCollection<>();
collection.add(1);
collection.add(4);
collection.add(10);
collection.add(5);
System.out.println(collection);
System.out.println(collection.get(3) + " " + collection.size());
}
}
The MyCollection.java starts like this
package MyJavaClasses.utility;
import java.util.*;
/**
* #author Rishav Agarwal
* #param <T> This describes the Type parameter
*/
public class MyCollection<T> implements Cloneable {
//...
}
I'm developing an application that requires two main() classes, first one for the actual application, and a second one for the JMX connectivity and management. The issue I'm facing is even after ensuring the first main() is executed and initializes the variables, when the second main() runs but does not see those variables and throws null exception.
Application main():
public class GatewayCore {
private static Logger logger = Logger.getLogger(GatewayCore.class);
private static ThreadedSocketInitiator threadedSocketInitiator;**
private static boolean keepAlive = true;
//private static Thread mqConnectionManager;
public static void main(String args[]) throws Exception {
__init_system();
__init_jmx();
__init_mq();
while(keepAlive) {}
}
private static void __init_system() {
try {
logger.debug("__init_system:: loading configuration file 'sessionSettings.txt'");
SessionSettings sessionSettings = new SessionSettings(new FileInputStream("sessionSettings.txt"));
logger.info("\n" + sessionSettings);
MessageStoreFactory messageStoreFactory = new FileStoreFactory(sessionSettings);
LogFactory logFactory = new FileLogFactory(sessionSettings);
MessageFactory messageFactory = new DefaultMessageFactory();
Application sessionManager = new SessionManager();
threadedSocketInitiator = new ThreadedSocketInitiator(sessionManager, messageStoreFactory, sessionSettings, logFactory, messageFactory);
...
public static ThreadedSocketInitiator getThreadedSocketInitiator() {
return threadedSocketInitiator; }
Secondary main() class, meant to be invoked for JMX-Mbean purpose:
public class RemoteCommandLine {
private static Logger logger = Logger.getLogger(RemoteCommandLine.class);
private static final String JMX_SERVICE_URL_PREFIX = "service:jmx:rmi:///jndi/rmi://";
private static final String HOST = "localhost";
private static String PORT = "24365";
private static JMXConnectionInstance jmxConnectionInstance;
private static boolean keepAlive = true;
public static void main(String[] args) throws IOException, MalformedObjectNameException, ConfigError {
logger.debug(GatewayCore.getThreadedSocketInitiator());
...
From command line, I first run:
java -classpath etdfix.jar:slf4j-api-1.7.25.jar:mina-core-2.0.16.jar:quickfixj-all-2.0.0.jar -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=24365 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false com.scb.etdfix.GatewayCore sessionSettings.txt
Wait for the inits to complete, ensuring threadedSocketInitiator has been assigned, then:
java -classpath etdfix.jar:slf4j-api-1.7.25.jar:mina-core-2.0.16.jar:quickfixj-all-2.0.0.jar com.scb.etdfix.JMX.RemoteCommandLine
Which ultimately throws a null pointer exception for the line:
logger.debug(GatewayCore.getThreadedSocketInitiator());
My plan is to have the first main() initialize the object, then pass to the second main() to do further method calls using the same object (it must be the same instance) when it is manually invoked. Both classes are compiled together into the same JAR. Please advise on how I can get around this issue or anything I can do to debug this further.
In fact, I'm thinking that this may not be possible as when the 2nd main() is invoked, from its POV the first main() isn't initialized. Therefore I should approach this by considering that they are two separate entities.
Each process (each java command) is completely separate, whether they run the same main() or not. This is a feature—the alternative would be to have unrelated parts of the system collide whenever they used a common utility.
That said, nothing stops you from calling GatewayCore.main() yourself (with the real command line or whatever other argument list) if you want to reuse its logic. It might be a good idea, though, to factor out the common code as another function: main() has many special responsibilities and programmers do not usually expect it to be called within a program.
I'm trying to create SpellChecker program through api, here is my code
SpellCheck.java
package com.spell;
import org.xeustechnologies.googleapi.spelling.SpellChecker;
import org.xeustechnologies.googleapi.spelling.SpellCorrection;
import org.xeustechnologies.googleapi.spelling.SpellResponse;
public class SpellCheck {
public static void main(String[] args)
{
SpellChecker checker = new SpellChecker();
SpellResponse spellResponse = checker.check( "helloo worlrd" );
for( SpellCorrection sc : spellResponse.getCorrections() )
System.out.println( sc.getValue() );
}
}
Dependencies
Error I got after running it:
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.spell.SpellCheck.main(SpellCheck.java:12)
Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
at org.apache.log4j.Logger$PrivateManager.getContext(Logger.java:59)
at org.apache.log4j.Logger.getLogger(Logger.java:41)
at org.xeustechnologies.googleapi.spelling.SpellChecker.(SpellChecker.java:50)
... 1 more
It looks like org.xeustechnologies.google.api.spelling.SpellChecker uses log4j and you are using slf4j. Try adding log4j-over-slf4j to the classpath to bridge log4 to use slf4j.
I have enum DebugMode in a separate file DebugMode.java.
package core;
public enum DebugMode {
Disabled, Console, Dialog, All
}
Then I have a class Debug in Debug.java.
package core;
public class Debug {
private static DebugMode debug = DebugMode.All;
public static void Message(String str) {
//some unrelated stuff
}
}
But for some reason it gives me error to this string:
private static DebugMode debug = DebugMode.All;
The error is:
Caused by: java.lang.RuntimeException: Uncompilable source code - class DebugMode is public, should be declared in a file named DebugMode.java
at core.DebugMode.<clinit>(Debug.java:6)
... 3 more
Java Result: 1
I just don't understand what's the problem... can someone help me figure it out?