everyone.
I used openjdk-7 on arch linux. I started to learn Java recently, and encountered such a problem:
I created a file at /home/hqwrong/Code/java/mew/Mouth.java:
package mew;
public class Mouth{
public static void main(String argv[]){
pickle.Say s = new pickle.Say();
}
}
and another one at /home/hqwrong/Code/java/pickle/Say.java :
package pickle;
public class Say{
public Say(){
System.out.println("Say");
}
}
I compiled Say.java to Say.class,using:
$ cd /home/hqwrong/Code/java/pickle
$ javac Say.java
which is successful.
I compiled Mouth.java ,using:
$ cd ../mew
$ export CLASSPATH=.:/home/hqwrong/Code/java/
$ javac Say.java
no error message.
But after I type:
$ java Say
I got:
Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.mew
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:649)
at java.lang.ClassLoader.defineClass(ClassLoader.java:785)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:472)
It’s same when I use:
$ java -cp $CLASSPATH Say
I need your help,please?
Since there is no good answer yet, I’ll post mine.
First, you should really have a separate folder for your classes and your sources. I suggest using
java/srcfor your sources, andjava/classesfor your classes. Since the classes are stored in the classes folder, this is the one that should be in the classpath.The folder tree of your sources should then match your package tree. This means that the class mew.Mouth must contain the line
package mew, be defined in the Mouth.java file, in thejava/src/mewfolder.To compile your classes, put you in the
java/srcdirectory, and use the following command:The compiler will automatically generate the folder structure matching the package structure in the classes directory. If you make structural modifications in your source tree, just remove everything in the classes folder, and recompile everything.
To run your classes, you must refer to their fully qualified name. And the folder containing your package tree (the
java/classesfolder) must be in the classpath. Once this is done, from everywhere, you can useNote that, as you have discovered, the
javaandjavaxpackages are reserved. You can’t use them for your own classes.