Exception in thread "main" java.lang.ClassFormatError: [duplicate] - java

This question already has an answer here:
How to properly install and configure JSF libraries via Maven?
(1 answer)
Closed 7 years ago.
In my Java project, it used to work perfectly without any issue.
But when I tried to run it now, it gives me the following error. I googled it, but couldn't find a proper solution.
Below is my Java class:
public class MyClass{
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
DB.connect();
Login login = new Login();
login.setVisible(true);
}
}
The error is:
Exception in thread "main" java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file mypackage/Login
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at mypackage.MyClass.main(MyClass.java:38)
Java Result: 1
If anybody knows the solution, please help me to solve this issue.
Thanks

Exception in thread "main" java.lang.ClassFormatError: Absent Code
attribute in method that is not native or abstract in class file
mypackage/Login
This seems to indicate something is wrong with your Login class - possibly unimplemented method(s).

I experienced the same problem. Actually it's was a Netbean issue for me...
Go in your project properties, then in Compiling disable Compile on Save.
Clean and Build your project, then try to run it.
Other solution to try, take a look at your Source/Binary format in your project properties (sources), and make sure you use the right one. Check the JDK platform used by libraries too.
I've update to JDK1.7(default) for libraries and JDK6 for source and then it works for me.
Other possible answers here :
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file "name of class"
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/faces/webapp/FacesServlet

check the package name on top. typo for "mypacakge"?

Related

im4java throws FileNotFoundException error

I need to use ImageMagic in my java project.
I already installed ImageMagic-7.0.3 on Windows 10
(command line works fine)
Then, i added dependency to im4java in maven file. When i try to do some action like:
public static void main(String[] args) {
String imPath="C:\\Program Files\\ImageMagick-7.0.3-Q16";
ConvertCmd cmd = new ConvertCmd();
cmd.setSearchPath(imPath);
IMOperation op = new IMOperation();
op.addImage("biuro.jpg");
op.negate();
op.addImage("biuro_new.jpg");
try {
cmd.run(op);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
System.out.println("works");
}
i get following error
org.im4java.core.CommandException: java.io.FileNotFoundException: convert
at org.im4java.core.ImageCommand.run(ImageCommand.java:219)
at Main.main(Main.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.io.FileNotFoundException: convert
at org.im4java.process.ProcessStarter.searchForCmd(ProcessStarter.java:661)
at org.im4java.process.ProcessStarter.startProcess(ProcessStarter.java:399)
at org.im4java.process.ProcessStarter.run(ProcessStarter.java:312)
at org.im4java.core.ImageCommand.run(ImageCommand.java:215)
... 6 more
I went trough half of Internet. Read half of google. There was only one small advice saying "have you installed Visual C++ Redistributable and reboot?" That was the solution.
ImageMagick worked in command line, so I did not expected requirement of that type. Moreover I did not find a thing about it in both - im4java and ImageMagick reference.
Hope this will be helpful, and noone ever will waste about 5h of life searching the answer.
Set the user variable under environment variable,Variable name as IM4JAVA_TOOLPATH
and Variable Value as C:\Program Files\ImageMagick-7.0.3-Q16.
after that kill all the java process and try to run the program.
Other way you can set the global search path like below:
String myPath="C:\\Programs\\ImageMagick;";
ProcessStarter.setGlobalSearchPath(myPath);
This will override your user environmental variable.
Also refer the documentation for more setup related info in detail http://im4java.sourceforge.net/docs/dev-guide.html
After spending a lot a hours in order to research why I had that issue, the solution is : you need to uninstall then reinstall ImageMagick with "Install legacy utilities (e.g. convert)" during the setup.

Loading a jar at runtime causes a NoClassDefFoundError/ClassNotFoundException

Summary: Loading a jar from a running Java program causes a NoClassDefFoundError caused by a ClassNotFoundException caused by inter-class dependencies (e.g. import statements). How can I get around it?
The problem in more detail:
I am attempting to programmatically load a jar file -- let's call it "Server" -- into the Java Virtual Machine through my own Java program -- let's call it "ServerAPI" -- and use extension and some other tricks to modify the behavior of and interact with Server. ServerAPI depends on Server, but if Server is not present, ServerAPI still has to be able to run and download Server from a website.
To avoid errors caused by ServerAPI loading without satisfying its dependencies from Server, I have made a launcher -- let's call it "Launcher" -- that is intended to download Server and set up ServerAPI as necessary, then load Server and ServerAPI, then run ServerAPI.
However, when I attempt to load jars from Launcher, I get errors caused because the ClassLoaders are unable to resolve the other classes in the file that the class it's loading depends on. In short, if I try to load Class A, it will throw an error if A imports B because I haven't loaded B yet. However, if B also imports A, I'm stuck because I can't figure out how to load two classes at once or how to load a class without the JVM running its validation.
Why all the restrictions have led me to this problem:
I am attempting to modify and add to the behavior of Server, but for complicated legal reasons, I cannot modify the program directly, so I have created ServerAPI that depends on and can tweak the behavior of Server from the outside.
However, for more complicated legal reasons, Server and ServerAPI cannot simply be downloaded together. Launcher (see above) has to be downloaded with ServerAPI, then Launcher needs to download Server. Finally, ServerAPI can be run using Server as a dependency. That's why this problem is so complex.
This problem will also apply to a later part of the project, which will involve a plugin-based API interface that needs to be able to load and unload plugins from jar files while running.
Research I have already done on this problem:
I have read through and failed to be helped by:
this question, which only addresses the issue of a single method and does not address inter-class dependency errors;
this question, which will not work because I cannot shut down and restart the program every time a jar is loaded or unloaded (mainly for the plugin part I briefly mentioned);
this question, which only works for situations where the dependencies are present when the program starts;
this question, which has the same problem as #2;
this question, which has the same problem as #3;
this article, from which I learned about the hidden loadClass(String, boolean) method, but trying with true and false values did not help;
this question, which has the same problem as #1;
and more. Nothing has worked.
//EDIT:
Attempts I have made so far:
I have tried using URLClassLoaders to load the jar using the JarEntries from the JarFile similar to this question. I tried this both by using and calling a URLClassLoader's loadClass(String) method and by making a class that extends URLClassLoader so that I could utilize loadClass(String, boolean resolve) to try to force the ClassLoader to resolve all the classes it loads. Both ways, I got this same error:
I couldn't find the class in the JarEntry!
entry name="org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapAttributeConverter.class"
class name="org.apache.logging.log4j.core.appender.db.jpa.converter.ContextMapAttributeConverter"
java.lang.NoClassDefFoundError: javax/persistence/AttributeConverter
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at Corundum.launcher.CorundumClassLoader.load(CorundumClassLoader.java:52)
at Corundum.launcher.CorundumLauncher.main(CorundumLauncher.java:47)
Caused by: java.lang.ClassNotFoundException: javax.persistence.AttributeConverter
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 12 more
//END EDIT
//EDIT 2:
Here is a sample of the code that I used to load a class while trying to resolve it. This was inside a class that I made that extends URLClassLoader. On the line beginning with Class<?> clazz = loadClass(, I have tried using true and false as the boolean argument; both attempts resulted in the same error above.
public boolean load(ClassLoadAction class_action, FinishLoadAction end_action) {
// establish the jar associated with this ClassLoader as a JarFile
JarFile jar;
try {
jar = new JarFile(jar_path);
} catch (IOException exception) {
System.out.println("There was a problem loading the " + jar_path + "!");
exception.printStackTrace();
return false;
}
// load each class in the JarFile through its JarEntries
Enumeration<JarEntry> entries = jar.entries();
if (entries.hasMoreElements())
for (JarEntry entry = entries.nextElement(); entries.hasMoreElements(); entry = entries.nextElement())
if (!entry.isDirectory() && entry.getName().endsWith(".class"))
try {
/* this "true" in the line below is the whole reason this class is necessary; it makes the URLClassLoader this class extends "resolve" the class,
* meaning it also loads all the classes this class refers to */
Class<?> clazz = loadClass(entry.getName().substring(0, entry.getName().length() - 6).replaceAll("/", "."), true);
class_action.onClassLoad(this, jar, clazz, end_action);
} catch (ClassNotFoundException | NoClassDefFoundError exception) {
try {
close();
} catch (IOException exception2) {
System.out.println("There was a problem closing the URLClassLoader after the following " + exception2.getClass().getSimpleName() + "!");
exception.printStackTrace();
}
try {
jar.close();
} catch (IOException exception2) {
System.out.println("There was a problem closing the JarFile after the following ClassNotFoundException!");
exception.printStackTrace();
}
System.out.println("I couldn't find the class in the JarEntry!\nentry name=\"" + entry.getName() + "\"\nclass name=\""
+ entry.getName().substring(0, entry.getName().length() - 6).replaceAll("/", ".") + "\"");
exception.printStackTrace();
return false;
}
// once all the classes are loaded, close the ClassLoader and run the plugin's main class(es) load() method(s)
try {
jar.close();
} catch (IOException exception) {
System.out.println("I couldn't close the URLClassLoader used to load this jar file!\njar file=\"" + jar.getName() + "\"");
exception.printStackTrace();
return false;
}
end_action.onFinishLoad(this, null, class_action);
System.out.println("loaded " + jar_path);
// TODO TEST
try {
close();
} catch (IOException exception) {
System.out.println("I couldn't close the URLClassLoader used to load this jar file!\njar file=\"" + jar_path + "\"");
exception.printStackTrace();
return false;
}
return true;
}
//END EDIT 2
I realize that there must be a simple solution to this, but for the life of me I cannot seem to find it. Any help would make me eternally grateful. Thank you.
Embarassingly, I found that the answer was that the error message was telling the truth. javax.persistence.AttributeConverter, the class that the loader was claiming was not present, was not in the jar.
I fixed the issue by loading only the main class and the ClassLoader all references classes, essentially loading all the classes in the jar that are used in the program, which is all I need.
Now, I could have sworn that I checked for this before and found that class; I figure I must have actually checked the Apache open source repository for the class rather than the actual Server when I checked that. I can't remember.
In any case, AttributeConverter is missing. I don't know how or why they managed to compile a jar with missing dependencies, but I guess their main processes never use that part of the code, so it never threw errors.
I'm sorry to have wasted everyone's time...including my own. I have been stuck on this problem for a while now.
Moral of this story:
If you're trying to load an executable jar, don't bother loading all the classes in a jar unless you actually have to. Just load the main class; that will load everything the program needs to run.
//EDIT:
I have now started having the same error, but it does not appear until I attempt to call a method from a loaded class. The question is apparently still open. Please downvote and disregard this answer.

java.lang.NoClassDefFoundError: com/sun/logging/LogDomains when running unit tests

I'm running a unit test that throws this error:
java.lang.NoClassDefFoundError: com/sun/logging/LogDomains
at com.sun.enterprise.util.ORBManager.<clinit>(ORBManager.java:93)
at com.sun.enterprise.naming.SerialInitContextFactory.<clinit>(SerialInitContextFactory.java:65)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:46)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:654)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:175)
myCode
My code is this:
try {
Context c = new InitialContext(); //line that errors
return (T) c.lookup(name);
} catch (NamingException ne) {
log.error(ne.getMessage(), ne);
throw new RuntimeException(ne);
}
How do I get around this issue?
It seems like this answer would work, except for the huge deal breaker I mention in a comment:
The problem with this is that they seem to have exploded a bunch of jars and packaged them back together inside glassfish-embedded-all. You better hope you're using the same slf4j version they packaged in there, because they didn't give a way to exclude what they give you. There has got to be a better way.
FWIW, I'm deploying to Glassfish 3.
Perhaps I need to prevent my unit test from getting to this line. But it feels weird that I get an NoClassDefFoundError Why is this happening?

Problems in running a modified Java code

I modified a Java code in Eclipse on my laptop with a Windows O.S. Now I have to run the code on a linux O.S. via SSH. I copied all the files and I tried to compile the code. The compilation went well, so there were no errors in the code. Anyway, when I tried to run it, the following errors appeared on the shell:
[ac6411#epigenetic models]$ java TanaModel
Exception in thread "main" java.lang.NoClassDefFoundError: TanaModel (wrong name: models/TanaModel)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
Do you know what kind of the problem is?I'm new in Java coding, so I don't know how to solve it. Thank you.
wrong name: models/TanaModel
This means it expected to find TanaModel.class under the models directory, but found it somewhere else (maybe the current directory?). Put the class file in a the models directory, and run it as
java models.TanaModel
Java expects class files to be organized in directories that mirror the package structure you used in your source code.
java.lang.NoClassDefFoundError: TanaModel (wrong name: models/TanaModel) at
What command did you run, I'm guessing java TanaModel ?
Most likely your TanaModel is declared to be in package models;
Try calling it like this:
java models.TanaModel
If it is a Eclipse security issue, this would help.
//Java Code
try
{
AccessController.doPrivileged(new PrivilegedAction<Object>()
{
public Object run()
{
try
{
// Insert code here to do required action (get or open file)
}
catch (Exception e)
{
// Insert code to catch exception from trying to do above action
}
}
}
);
}
catch(Exception e)
{
// Insert code to catch failed doPrivileged()
}
When you try to run your program, try calling it like this:
java models.TanaModel

java.lang.NoClassDefFoundError: Could not initialize class java.net.ProxySelector

I'm running into a problem with a java app constantly throwing:
java.lang.NoClassDefFoundError: Could not initialize class java.net.ProxySelector.
I am running Suse Linux 10.3 and running java 1.6.0. My CLASSPATH is set to
/usr/lib/jvm/jre-1.6.0-openjdk/lib.
No other users seem to be having this error so I'm assuming its my setup. For those wondering the app is yamj (http://code.google.com/p/moviejukebox/)
Any ideas as to what maybe missing or what I maybe doing wrong?
Edit the full trace of the error is as follows:
java.lang.NoClassDefFoundError: Could not initialize class java.net.ProxySelector
at sun.net.www.protocol.http.HttpURLConnection$5.run(HttpURLConnection.java:736)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:732)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:672)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:997)
at com.moviejukebox.thetvdb.tools.XMLHelper.getEventReader(XMLHelper.java:19)
at com.moviejukebox.thetvdb.model.Mirrors.(Mirrors.java:30)
at com.moviejukebox.thetvdb.TheTVDB.(TheTVDB.java:37)
at com.moviejukebox.plugin.TheTvDBPlugin.(TheTvDBPlugin.java:57)
at sun.reflect.GeneratedConstructorAccessor2.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at com.moviejukebox.plugin.DatabasePluginController.getMovieDatabasePlugin(DatabasePluginController.java:96)
at com.moviejukebox.plugin.DatabasePluginController.access$000(DatabasePluginController.java:30)
at com.moviejukebox.plugin.DatabasePluginController$1.initialValue(DatabasePluginController.java:44)
at com.moviejukebox.plugin.DatabasePluginController$1.initialValue(DatabasePluginController.java:39)
at java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:160)
at java.lang.ThreadLocal.get(ThreadLocal.java:150)
at com.moviejukebox.plugin.DatabasePluginController.scan(DatabasePluginController.java:70)
at com.moviejukebox.MovieJukebox.updateMovieData(MovieJukebox.java:1051)
at com.moviejukebox.MovieJukebox.access$100(MovieJukebox.java:80)
at com.moviejukebox.MovieJukebox$4.call(MovieJukebox.java:613)
at com.moviejukebox.MovieJukebox$4.call(MovieJukebox.java:600)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java
ProxySelector is an abstract class. Are you trying to instantiate it directly?
My CLASSPATH is set to
/usr/lib/jvm/jre-1.6.0-openjdk/lib.
don't think that should be in your CLASSPATH
try clearing the CLASSPATH and running it
Firstly, you shouldn't have to put "/usr/lib/jvm/jre-1.6.0-openjdk/lib" on your classpath. The "java" command should put all of the standard J2SE libraries on the bootclasspath without you doing anything.
Second, it would help if you gave us the full stacktrace, not just the exception message. I suspect that the real problem is that java.net.ProxySelector (or something it depends on) is failing during static initialization. But only a stacktrace would confirm that.
Since it's second result in google search on this error, I want to post this piece of code I found at some forum that helped me with the same exception. Cannot explain in details - it was just a quick test project for me, so I didn't have time for deeper investigation.
static {
try {
Class c = Class.forName("sun.net.spi.DefaultProxySelector");
if (c != null && ProxySelector.class.isAssignableFrom(c)) {
theProxySelector = (ProxySelector) c.newInstance();
}
} catch (Exception e) {
theProxySelector = null;
}
}

Categories