2013-02-06 53 views
3

我以前使用過java -classpath通配符擴展功能並且成功。我目前正在遇到一個奇怪的問題。java類路徑通配符行爲

通配符應該擴展到指定文件夾中的每個jar。下面是從Oracle報價:

Class path entries can contain the basename wildcard character *, 
which is considered equivalent to specifying a list of all the files 
in the directory with the extension .jar or .JAR. For example, the 
class path entry foo/* specifies all JAR files in the directory 
named foo. A classpath entry consisting simply of * expands to a 
list of all the jar files in the current directory. 

This is a link to Oracle doc on Java 6 on the subject of classpath.

行爲我看到這相矛盾。這裏有3次運行。第一個明確命名jar,所以它的工作原理。其他人使用通配符並失敗。爲什麼?這對我很重要,因爲我依賴通配符(其他地方),因此對這種意外行爲的理解對我很重要。

#!/bin/bash 

printf "The EV is...\n" 
echo $CLASSPATH 
printf "The working directory is...\n" 
pwd 
printf "Directory listing...\n" 
ls 
printf "END of directory listing.\n" 

printf "Test with named jar.\n" 
java -javaagent:../sizeof/sizeof.jar -classpath ./testsizeof.jar info.zqxj.test.Tester 

printf "Test with star.\n" 
java -javaagent:../sizeof/sizeof.jar -classpath * info.zqxj.test.Tester 

printf "Test with dot slash star.\n" 
java -javaagent:../sizeof/sizeof.jar -classpath ./* info.zqxj.test.Tester 

輸出:

The EV is... 

The working directory is... 
/home/b/Documents/workspace/testsizeof 
Directory listing... 
bin run.sh src testsizeof.jar 
END of directory listing. 
Test with named jar. 
40 
Test with star. 
Exception in thread "main" java.lang.NoClassDefFoundError: run/sh 
Caused by: java.lang.ClassNotFoundException: run.sh 
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190) 
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306) 
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) 
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247) 
Could not find the main class: run.sh. Program will exit. 
Test with dot slash star. 
Exception in thread "main" java.lang.NoClassDefFoundError: //run/sh 
Caused by: java.lang.ClassNotFoundException: ..run.sh 
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190) 
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306) 
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) 
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247) 
Could not find the main class: ./run.sh. Program will exit. 

回答

5

解決方案,雙引號類路徑參數。示例:-classpath "*"這在命令行以及bash腳本中是必需的。

隨後補遺:

此外,注意-classpath "~/folder/*"失敗,但-classpath ~/folder/"*"還是不錯的。引用通配符,但不要引用~。看起來您需要操作系統來解釋~,但您需要引用*通配符,因爲您想將它傳遞給java以用Java進行擴展。

還請注意,您不應要求java擴大*.jar,因爲這會產生意想不到的結果。 Java規範指出,正確的通配符僅僅是*