3

java -classpath以前成功地使用过通配符扩展功能。我目前遇到了一个奇怪的问题。

通配符应该扩展到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.

这是关于类路径主题的 Java 6 上的 Oracle 文档的链接。

我看到的行为与此相矛盾。这里有 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.
4

1 回答 1

6

解决方案,双引号类路径参数。示例: -classpath "*" 这在命令行和 bash 脚本中都是必需的。

随后的附录:

此外,请注意-classpath "~/folder/*"失败但-classpath ~/folder/"*"很好。引用通配符但不要引用~. 似乎您需要操作系统来解释~,但您需要引用*通配符,因为您想将它传递java给以 Java-fashion 进行扩展。

另请注意,您不应要求java扩展*.jar,因为这会产生意想不到的结果。Java 规范说正确的通配符是*唯一的。

于 2013-02-06T06:15:33.910 回答