Subscribe to CodeScissors        RSS Feed
-----

Calling a Java-Class from the Terminal

Icon Leave Comment
Lately, I played around with some Socket-Connection based Server things in Java. The Server Class I wrote was without any GUI things (e.g. Swing/AWT) just for the Console (using System.out.println() for reporting).

So I wanted to call the Class but i only got this from my Terminal:
Exception in thread "main" java.lang.NoClassDefFoundError: Server (wrong name: lotto/Server)
        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)
Could not find the main class: Server.  Program will exit.



WTF? Now, what was my mistake? I navigated into the directory with the .class-Files and used java Server.class. What is the Problem?

Mistake Nr. 1
Calling a Class in Java is not like calling a compiled C++ Program (on Windows), where you don't need the file-extension. In Java, you must not use it!
Because you're calling the Class "Server", not the File "Server.class" (The File "Server.class" contains the "Server"-Class, but since the name of your File can only be the Same as it's Class, Java knows where to look for the File).

Mistake Nr. 2
My Server-Class was created in the Package "lotto" (Because it's a lotto-Server). I navigated right into the bin-Directory created by Eclipse and than into the lotto-Directory, which represents the Package "lotto". The Package-Name is also noted on the top of the Java-File (probably at it's first line).
So if you want to call the Class "Server" in the Package "lotto", you can't navigate into the "lotto"-Directory, you need to stay in the "bin"-Directory and make the Call using Java's point-Notation:
# ls
<DIR> lotto
# ls lotto
<FILE> Server.class
<FILE> Client.class
# java lotto.Server


This calls the Server-Class in the "lotto"-Package. And, it works!

Greetings: Luke

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

Recent Entries

2 user(s) viewing

2 Guests
0 member(s)
0 anonymous member(s)