I have a code below. I can compile and run it normally in NetBeans. But with javac/java, I cannot run it normally. What do I miss?
The code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/* the original code is from link: http://edu.qudong.com/safe/base/Javascript/shilidaima/20080514/12527.html */
package gendemo;
/**
*
* @author tomxue
*/
class Gen2 {
private Object ob; //定义一个通用类型成员
public Gen2(Object ob) {
this.ob = ob;
}
public Object getOb() {
return ob;
}
public void setOb(Object ob) {
this.ob = ob;
}
public void showTyep() {
System.out.println("T的实际类型是: " + ob.getClass().getName());
}
}
public class GenDemo2 {
public static void main(String[] args) {
//定义类Gen2的一个Integer版本
Gen2 intOb = new Gen2(new Integer(88));
intOb.showTyep();
int i = (Integer) intOb.getOb();
System.out.println("value= " + i);
System.out.println("----------------------------------");
//定义类Gen2的一个String版本
Gen2 strOb = new Gen2("Hello Gen!");
strOb.showTyep();
String s = (String) strOb.getOb();
System.out.println("value= " + s);
}
}
By javac, after compiling, I got below result.
tomxue@ubuntu:~/test$ javac GenDemo2.java
tomxue@ubuntu:~/test$ ls
Gen2.class GenDemo2.class GenDemo2.java
And then, if I run it like this:
tomxue@ubuntu:~/test$ java Gen2
Exception in thread "main" java.lang.NoClassDefFoundError: Gen2
Caused by: java.lang.ClassNotFoundException: Gen2
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
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)
tomxue@ubuntu:~/test$ java GenDemo2
Exception in thread "main" java.lang.NoClassDefFoundError: GenDemo2
Caused by: java.lang.ClassNotFoundException: GenDemo2
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
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)
What is wrong with it?
The problem is that java expects the directory structure to match the package name (“gendemo”), so it can’t find your classes. move your java file into a sub-directory named gendemo, then compile it from the top directory using
javac gendemo/GenDemo2.javaand run it usingjava -cp . gendemo.GenDemo2.