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
Related
This is the screenshot of my Eclipse project files.
I get the error below when I try to initiated a new Sound("Res/MouseClick.ogg") object in my class AudioPlayer at line 15.
package com.game;
import java.util.HashMap;
import java.util.Map;
import org.newdawn.slick.Music;
import org.newdawn.slick.Sound;
public class AudioPlayer {
public static Map<String, Sound> soundMap = new HashMap<String, Sound>();
public static Map<String, Music> musicMap = new HashMap<String, Music>();
public static void load() {
try {
soundMap.put("menu_sound", new Sound("Res/MouseClick.ogg")); // <- throws error
musicMap.put("music", new Music("Res/Background.ogg"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Music getMusic(String key) {
return musicMap.get(key);
}
public static Sound getSound(String key) {
return soundMap.get(key);
}
}
Exception in thread "main" java.lang.NoClassDefFoundError: sun/misc/Unsafe
at lwjgl/org.lwjgl.MemoryUtilSun$AccessorUnsafe.getUnsafeInstance(MemoryUtilSun.java:74)
at lwjgl/org.lwjgl.MemoryUtilSun$AccessorUnsafe.<init>(MemoryUtilSun.java:62)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166)
at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404)
at java.base/java.lang.Class.newInstance(Class.java:590)
at lwjgl/org.lwjgl.MemoryUtil.loadAccessor(MemoryUtil.java:324)
at lwjgl/org.lwjgl.MemoryUtil.<clinit>(MemoryUtil.java:66)
at lwjgl/org.lwjgl.openal.ALC10.alcOpenDevice(ALC10.java:202)
at lwjgl/org.lwjgl.openal.AL.init(AL.java:160)
at lwjgl/org.lwjgl.openal.AL.create(AL.java:138)
at lwjgl/org.lwjgl.openal.AL.create(AL.java:102)
at lwjgl/org.lwjgl.openal.AL.create(AL.java:201)
at slick/org.newdawn.slick.openal.SoundStore$1.run(SoundStore.java:295)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:310)
at slick/org.newdawn.slick.openal.SoundStore.init(SoundStore.java:292)
at slick/org.newdawn.slick.Sound.<init>(Sound.java:54)
at Wave/com.game.AudioPlayer.load(AudioPlayer.java:15)
at Wave/com.game.Game.<init>(Game.java:37)
at Wave/com.game.Game.main(Game.java:157)
Caused by: java.lang.ClassNotFoundException: sun.misc.Unsafe
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 23 more
From your posted IDE screenshot I can see that you are using
Java 12, and
the Java Module System (module-info.java)
Note that sun/misc/Unsafe is a (legacy) Java internal API which for that reason and by default is encapsulated (hidden) away when using the Java Module System.
In order for your application (and your used library) to access it, you need to explicitly include it in your module-info.java by adding requires jdk.unsupported;
Alternatively, you may also not use the Java Module System – in which case it should simply work. However, I recommend to continue using the module system.
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.
For some reason, I've been analyzing my own old jar file(unfortunately source code's been lost).
I know what part I'm going to find but can't remember where it is.
So decide to use byte buddy to get all the run flow of jar file. It's enough to log parameter values and return values of all methods in all classes(except library class, e.g, java.lang.*).
I tried sample codes with a little modification, but straggle with just an exception:
public static void premain(final String agentArgs,
final Instrumentation inst) {
System.out.println(
"+++Hey, look: I'm instrumenting a freshly started JVM!");
new AgentBuilder.Default()
.type(ElementMatchers.any())
.transform(new MetricsTransformer())
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.with(AgentBuilder.TypeStrategy.Default.REDEFINE)
.installOn(inst);
}
private static class MetricsTransformer implements AgentBuilder.Transformer {
#Override
public DynamicType.Builder<?> transform(
final DynamicType.Builder<?> builder,
final TypeDescription typeDescription,
final ClassLoader classLoader,
final JavaModule module) {
final AsmVisitorWrapper methodsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceMethods.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isMethod()));
final AsmVisitorWrapper constructorsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceConstructors.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isConstructor()));
return builder.visit(methodsVisitor).visit(constructorsVisitor);
}
private static class EnterAdvice {
#Advice.OnMethodEnter
static long enter() {
return System.nanoTime();
}
}
private static class ExitAdviceMethods {
#Advice.OnMethodExit(onThrowable = Throwable.class)
static void exit(#Advice.Origin final Executable executable,
#Advice.Enter final long startTime,
#Advice.Thrown final Throwable throwable) {
final long duration = System.nanoTime() - startTime;
System.out.println(duration);;
}
}
}
byte buddy's versions are 1.9.5, 1.7.11
jdk version: 1.8.0.191
and the Exception in the cmd:
E:\>cd E:\workshop\_android_studio\BounAgent\out\artifacts\BounAgent_jar
E:\BounAgent_jar>java -javaagent:BounAgent.jar -jar untitled.jar
Exception in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/matcher
/ElementMatcher
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown Sou
rce)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown So
urce)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.matcher.ElementMatche
r
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more
FATAL ERROR in native method: processing of -javaagent failed
Thanks in advance.
According to an article I found:
To launch your agent you must bundle the agent classes and resources in a jar, and in the jar manifest set the Agent-Class property to the name of your agent class containing the premain method. (An agent must always be bundled as a jar file, it cannot be specified in an exploded format.)
It appears that your agent JAR file ("BounAgent.jar") does not contain all of the dependencies in the correct form. Specifically, the bytebuddy classes are not in the JAR file. That is causing the agent classes to fail to load.
This question already has answers here:
Does the JVM throw if an unused class is absent?
(3 answers)
How to avoid NoClassDefFoundError thrown by unused code in Java
(3 answers)
Closed 1 year ago.
We use some optional libraries. This libraries will only access if available. But the JIT produce already NoClassDefFoundError in the constructor of the class with optional access.
public Configuration {
public boolean libraryAvailable() {
return false; // some configuration that signal that the library is not available
}
}
public class Foo {
public Foo() {
... do some things
}
public void callLater() {
...
if( libraryAvailable() ) {
xyz();
}
...
}
private void xyz() {
new OptionalClass(); // available at compile time but not at runtime
}
}
How can I prevent that the JIT will load all possible dependencies of my call before calling the constructor?
java.lang.NoClassDefFoundError: com/inet/OptionalClass
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getConstructor0(Class.java:3075)
at java.lang.Class.newInstance(Class.java:412)
...
Caused by: java.lang.ClassNotFoundException: com.inet.OptionalClass
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at com.inet.plugin.DependencyClassLoader.loadClass(DependencyClassLoader.java:104)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.inet.plugin.DependencyClassLoader.loadClass(DependencyClassLoader.java:138)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 9 more
Instead of importing your optional class, use Class.forName
try {
Class<?> act = Class.forName("com.bla.TestActivity");
MyInterface driver = act.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
You could write your own custom method as shown in below code to check if a class is available in classpath.
boolean result=false;
try {
Class.forName( "your.test.class" );
result=true;
} catch( ClassNotFoundException e ) {
//Class or Library is not available
}
return result;
The decoupling of class loading for unused code with a separate method only work if the constructor empty. If there is a constructor then you need to move the unused code in a separate class. This can also be an anonymous class.
For example:
new Object () { {
new OptionalClass();
} };
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 {
//...
}