Blanca Hdez Blanca Hdez - 1 month ago 12
Java Question

Using wildcards in java classpath

I am running a shell script that is supposed to execute a

main
method:

java -classpath /path/to/app/conf/lib/nameJar* com.example.ClassTest


In this point I get this exception:

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext
Caused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContext
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:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)


This is because the spring jars are located in another folder. SO I have changed the script:

java -classpath /path/to/app/conf/lib/nameJar*:/path/to/app/lib/spring* com.example.ClassTest


But with this script, the com.example.ClassTest can not be found. Any ideas about this issue?

Thanks in advance

Answer

The java classpath wildcard expansion is unusual.

From the docs:

Understanding class path wildcards

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.

So, what you need to specify is:

java -classpath /path/to/app/conf/lib/*:/path/to/app/lib/*

If you need only specific jars, you will need to add them individually. The classpath string does not accept generic wildcards like nameJar*, *.jar, spring* etc.

Read Setting multiple jars in java classpath for more information.

Comments