The Java classloader loads the first class it can find with a matching name. Is there any way to programmatically tell which one is loaded?
i.e., can I change the main below in a way that tells which ClassLoaderTest is loaded (other than invoking test()
)?
echo "public class ClassLoaderTest { public static String test() { return \"1\"; } }" > ClassLoaderTest.java
javac ClassLoaderTest.java
mkdir one
mv ClassLoaderTest.class one
echo "public class ClassLoaderTest { public static String test() { return \"2\"; } }" > ClassLoaderTest.java
javac ClassLoaderTest.java
mkdir two
mv ClassLoaderTest.class two
echo "public class Main { public static void main(String[] _) { System.out.println(ClassLoaderTest.test()); } }" > Main.java
javac Main.java
java -classpath one:two:. Main
java -classpath two:one:. Main
This outputs 1
then 2
based on the classpath order.