Unsure about reason behind NoClassDefFoundError - java

I have built a DLL which I am attempting to wrap Java code with, however I am having some troubles with running my Java program. I wrote a simple test DLL and Java program and am producing the same error, and although there are plenty of resources regarding NoClassDefFoundError online I can't seem to solve mine with any troubleshooting methods.
Here is my D:\Test1.Java file
public class Test1 {
static {
//System.loadLibrary("HeyLand");
System.load("D://HeyLand.dll");
}
public native void displayHeyLand();
public static void main (String[] args) {
Test1 t = new Test1();
t.displayHeyLand();
}
}
After compiling, attempting to run D:\Test1.classresults in the following:
D:\>java Test1.class
Exception in thread "main" java.lang.NoClassDefFoundError: Test1.class
Caused by: java.lang.ClassNotFoundException: Test1.class
at java.net.URLClassLoader.findClass(URLClassLoader.java:434)
at java.lang.ClassLoader.loadClass(ClassLoader.java:660)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:358)
at java.lang.ClassLoader.loadClass(ClassLoader.java:626)
Could not find the main class: Test1.class. Program will exit.
Why I am stumped :
1. I have set my classpath to be D:\, so I believe my class definition would be in the classpath, and I do not see how my compile-time and run-time classpaths could be any different.
2. I don't see how this could have anything to do with static initialization, and I believe the exception would look different.
Perhaps I'm just missing something incredibly simple, I am very newbie with Java.
Any help is greatly appreciated!

The classpath environmental variable is taking precedence over that in the java run command. You need to specify the class location (as well as removing the .class file extension)
java -cp . Test1

Java normal syntax for executing class file is
Java [<options>....} <class-name> [<arguments>....]
For example
java com.package.name.Test1
here how compiler works
1. Compiler search for complete class name
2. Load that class
3. check for main method - in the same class
4. Call main method with passed arguments in command line string.
Now following are the possibilities why your class may not found main method.
1 - forgot to include package name
I am new developer in java but I found when I run application using eclips or intellJ editor it gives different path and package name and execute code as I noticed it on command line edior. So make sure you are including package name
For example:
java com.package.name.Test1 instead of
java Test1
2. File name or pathname rather then class name
As I noticed output file is in different location. That why class file path was different.
java Test1.class
java com/package/name/Test1.class
3. Typo
also I noticed you are using
static {
//System.loadLibrary("HeyLand");
System.load("D://HeyLand.dll");
}
Is this function ? or constructor? If it is function then where is name of the function? You cant write code without any reference in classs

Related

From shell, is there a Java tool to check which compiled .class file(s) have a main method?

I'm putting together some (Python) scripts to help me automate some of my grading of hundreds of simple student Java repos. Not all of them have the same directory structure or naming of files. I've traversed them all and compiled them and if I make assumptions I can run them and test them, etc. But I'd like to know if there's a way I could find the "main" .class that has the main() method in it, so that I don't have to make assumptions about their file naming (which wouldn't work all the time anyway).
I'm aware of reflection, so yes, I know I could write another simple helper Java program to assist me in identifying it myself. But I was wondering if anything already exists (java command line option, tool from the jdk, etc.) to test a .class file to see if it is has the main() method in it.
I was wondering if anything already exists (java command line option, tool from the JDK, etc.) to test a .class file to see if it is has the main() method in it.
There is no tool or option in Java SE that does that directly.
I know I could write another simple helper Java program to assist me ...
It would be simpler to write a shell script that iterates a file tree, finds .class files, calls javap on them, and greps for a method with the appropriate main method signature.
Or you could do something similar on the source code tree.
(In retrospect, you should have set the assignment requirements so that the students had to use a specified class and package name for the class containing their main method. But it is too late for that now ...)
In the C++ days, distributing the headers files to use a shared object file was a big deal. People would get one or the other without both, and there was always the chance you'd get mis-matched versions.
Java fixed that with javap which prints the methods (and other major interfaces) of a compiled .class file.
To test if a class file has a main, run
javap SomeFile.class
which will list all public interfaces. Within that list, see if it has the "main entry point"
public static void main(java.lang.String[])
Now to handle this in mass, simply create a Python script that:
Locates all the relevant classes.
Runs javap on the class.
Reads the output for a method that matches (at the beginning, as there can be a variable number of Exceptions at the end "public static void main(java.lang.String[])
And you'll find all entry points.
Keep in mind that sometimes a single library or JAR file has many entry points, some of which are not intended as the primary entry point.
Well simply calling java -cp . <file> will either completely blow out if the class doesn't have a main method or will run the relevant code. Now, if the code fails to run right and errors out you may see it as the same effect as not having a main method.
public class HasMain {
public static void main(String[] args) {
System.out.println("Hit main");
}
}
public class HasDoIt {
public static void doIt(String[] args) {
System.out.println("Hit doIt");
}
}
public class WillBlowUp {
public static void main(String[] args) {
System.out.println("Hit blowUp");
throw new IllegalStateException("oops");
}
}
Using PowerShell:
PS D:\Development\sandbox> javac HasMain.java
PS D:\Development\sandbox> javac HasDoIt.java
PS D:\Development\sandbox> javac WillBlowUp.java
PS D:\Development\sandbox> java -cp . HasMain
Hit main
PS D:\Development\sandbox> $?
True
PS D:\Development\sandbox> java -cp . HasDoIt
Error: Main method not found in class HasDoIt, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
PS D:\Development\sandbox> $?
False
PS D:\Development\sandbox> java -cp . WillBlowUp
Hit blowUp
Exception in thread "main" java.lang.IllegalStateException: oops
at WillBlowUp.main(WillBlowUp.java:4)
PS D:\Development\sandbox> $?
False
So simply checking return values could be a quick way to test if the class has what you want, albeit any exit(1) type return will throw a false-false

Using native code in java

I want to create c library and use it in my java code on an Linux OS. I'm trying to understand and implement natural library concept.
I'm following this tutorial
http://diglib.stanford.edu:8091/~testbed/doc/JavaUsage/JNI/tutorial.txt
Which is helpful me to understand concept a little. However, I get errors when I try to do it myself. I searced for errors I am getting but none of solutions helped.
Main class code and class for natural library I wrote is as follows:
package natLib;
import natLib.getKeyPressed;
public class main {
public static void main(String[] args) {
getKeyPressed natlab=new getKeyPressed();
char c=natlab.keyboardPressedKey();
}
}
package natLib;
public class getKeyPressed {
static {
System.loadLibrary("natlab");
}
public native char keyboardPressedKey();
}
when I write "javac main.java"
I get errors like
"main.java:6: error: cannot find symbol
getKeyPressed natlab=new getKeyPressed();"
And when I skip for main and just do javac prcess for class with native method, try to obtain a header file
javah -jni getKeyPressed.class
Although there is a file as getKeyPressed.class, I get errors like:
"Exception in thread "main" java.lang.IllegalArgumentException: Not a valid class name: getKeyPressed.class"
I try it without .class extention it says
"Error: Could not find class file for 'getKeyPressed'."
It says that even when I make getKeyPressed class file by copying getKeyPressed.class.
It seems I am making a major mistake, any suggestions to solve this?
javah expects a fully qualified classname. (e.g. natLib.getKeyPressed, not just getKeyPressed)

Error: Could not find or load main class hello.world.HelloWorld

I am trying to run this project called "hello user". I am new to Java, so wrote a simple program that takes your name, and displays "Hello ". while Running it, I get the following error:
run:
Error: Could not find or load main class hello.world.HelloWorld
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
But when I run file HelloWorld.java, it does it fine
I am doing this on Netbeans IDE 7.2
Rather than the coding error, it could be related to IDE. Since the "Run File" runs okay, but 'Run Project" does not, I believe you have something to set up in IDE itself. Right click the project, and select "Set is as Main", now run the project. I am just giving it a guess, may not help you. But it worth a shot.If it does not help, please paste your code too.
Your class needs a public static void main(String[] args) function. And moreover I suspect that the error could be in the package.
If you want your class in <main_package>.<sub_package>, The directory structure is
- main_package
- sub_package
-HelloWorld.java
And be sure to write your class like this.
package main_package.sub_package;
public class HelloWorld {
public static void main(String[] args){
System.out.println("Hello " + args[o]);
}
}
This is all due to the naming convention in Java
You need to run the .class file containing the public static void main(String[] args) method..
Here, your HelloWorld.java file might contain a class with main() method.. So, you can run it..
This is because, execution of any Java program starts with the invocation of main().. JVM needs an entry point to your code.. Which is main().. If it doesn't find one.. It will not run..
So, make sure, whatever class file you are running, it should have main() method..
UPDATE :- And for the starting point, may be you can skip using packages.. Just go with plain Java class without packages..
This message can also appear in Eclipse (Juno 4.2.2 in my case) and I have found two potential causes for it.
In my cases:
1. a DTD was in error. I deleted the file and that solved the issue*.
2. having cleaned the project, an external Jar that I had built externally had been deleted as could be seen from Properties -> Java Build Path -> Libraries.*
*Having solved either of the above issues, it was necessary to restart Eclipse
if you are using intellij idea then just rebuilding (clean and build) project might solve your problem . because intellij might be still trying to load the old classes which are not there or changed
Make sure you call looks like below:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello user");
}
}
To run a Java class in stand alone mode, public static void main(String[] args) is the entry method, which is must.

'Exception in thread "main" java.lang.NoClassDefFoundError' when running java program from command line

What am I doing wrong here:
class Helo {
// main: generate some simple output
public static void main (String[] args) {
System.out.println ("Hello, world."); // print one line
System.out.println ("How are you?"); // print another
}
}
When I go into terminal I do:
cd ~
javac Atempt2.java (//that's the file name)
java Atempt2
and then it gives me this error message:
Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
So all in all this is what I do and what happens:
david-allenders-macbook-pro:~ davidallender$ cd ~
david-allenders-macbook-pro:~ davidallender$ javac Atempt2.java
david-allenders-macbook-pro:~ davidallender$ java Atempt2
Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
david-allenders-macbook-pro:~ davidallender$
I am very new at this so please explain things in a very simple manner.
Thanks.
Its been awhile since I've done any java work but I'm pretty sure your class name needs to match your file name.
javac uses the class name to generate the output not the filename.
So it will generate a Helo.class classfile.
java will take a class name and call the main function in the corresponding class file, here Hello.class.
The ClassNotFoundError is thrown because javac never generated an Atemp2 classfile as there is no Atemp2 class in your source file.
Rename your Atempt2.java to Hello.java to get going, then:
javac Helo.java
java Helo
See here for more discussion and the reasoning.
change:
class Helo
to
class Atempt2
in your source file.
A .java file that declares a class must have the file name match the declared class name.
The filename must match the name of the public class defined in the file. In this case, you would either have to name the file "Helo.java" or renamed the class to Atempt2.
This is the very basic to start with java programming.Any program you write the name of the file must match with the public class of the program.
Here in your program public class of the file is Helo so your file name must be Helo.java.Here the compiler is able to compile but JVM will search for Helo.class file to run. As there is no Helo.class file you are getting runtime Exception Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
to complement josefx's answer.
The argument to the compiler (javac) is the name of the file or files to compile (as you did).
On the other side, the virtual machine (java) gets the name of the class whose main method is to be executed.
One option would be
javac Atempt2.java // the file name
java Helo // the class name
Normally it is a good idea to have the file named the same way as the class. For public class this is a must (checked by compiler).

Java Command Line Trouble with Reading a Class from a Jar Archive

I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance
Here's a concrete example of what does work, so you can compare your own situation.
Take this code and put it anywhere, in a file called MainClass.java. (I've assumed a directory called src later. Normally you'd arrange the source to match the package, of course.)
package archiveFolder;
public class MainClass
{
public static void main(String[] args)
{
System.out.println("I'm MainClass");
}
}
Then run each of these commands:
# Compile the source
javac -d . src/MainClass.java
# Build the jar file
jar cf archive.jar archiveFolder
# Remove the unpackaged binary, to prove it's not being used
rm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows
# Execute the class
java -cp archive.jar achiveFolder.MainClass
The result:
I'm MainClass
How are you building your jar file? Is the code in the appropriate package?
Does theMainClassName class have the following package line at the top:
package archiveFolder
You need the class file to be in the same directory structure as the declared package. So if you had something like:
org/jc/tests/TestClass.class
its source file would have to look like this:
package org.jc.tests;
public class TestClass {
public static void main(String[] args) {
System.out.printf("This is a test class!\n");
}
}
Then you could use the following to create the jar file and run it from the command line (assuming the current directory is at the top level, just above org):
$ jar -cf testJar.jar org/jc/tests/*.class
$ java -cp testJar.jar org.jc.tests.TestClass
Perhaps with java -jar archive.jar?
Of course, it supposes the manifest points to the right class...
You should give the exact message you got, it might shed more light.
EDIT: See Working with Manifest Files: The Basics for information on setting the application entry point (Main class) in your jar manifest file.
Usually this happens when a dependent class (static member) is not found - like this, using log4j:
public class MyClass {
private static Logger log = Logger.getLogger("com.example");
}
The reason is that the initialization of such a static member can be understood as part of the class loading - errors causing the class not to be available (loadable), resulting in the error you described.
Static constructors are another possible reason:
public class MyClass {
static {
// <b>any</b> error caused here will cause the class to
// not be loaded. Demonstrating with stupid typecast.
Object o = new String();
Integer i = (Integer) o;
}
}
I think others have covered some common stuff here. I'd jar tf the jar and make sure the class is listed. I'd also double-check that the class is public and the method is "public static void main(String[] arg)".

Categories

Resources