user8472 user8472 - 6 months ago 29
Java Question

Commons Math: java.lang.ClassNotFoundException

I have this tiny bit of Java code:

import java.io.*;
import org.apache.commons.math3.linear.*;

class Test
{
public static void main(String[] args){
RealVector alpha= MatrixUtils.createRealVector(new double[10]);
System.out.println(alpha.getEntry(0));
}
}


I can compile it successfully using
javac Test.java -cp .;commons-math.jar

But when I try to run it using
java Test -cp .;commons-math.jar
, it throws up this:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/ma
th3/linear/MatrixUtils
at Test.main(Test.java:9)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.math3.linear.Mat
rixUtils
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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)
... 1 more


From the Googling I did, a
ClassNotFoundException
usually occurs when your classpath isn't pointing to the right location. But since my code compiles, I don't see why it shouldn't execute. Any ideas?

Answer

If you type java into a command window you actually get how to setup a command to start a class file correctly:

Usage: java [-options] class [args...] (to execute a class) or java [-options] -jar jarfile [args...] (to execute a jar file)

"-cp" is an option so it goes before the class name

So a command script would look like this:

java -cp <SEMICOLON_SEPARETE_LIST_OF_LOCATIONS> qualified.path.to.MainClass <ARGUMENTS>
Comments