Is there a way to programmatically tell the source of a Java class?

The Java classloader loads the first class that it can find with the appropriate name. Is there a way to programmatically determine which one is loaded?

ie, can I change the main one below, which tells which ClassLoaderTest is loading (except for the call 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 2in accordance with the order of the class path.

+4
source share
2 answers

getClass().getProtectionDomain().getCodeSource().getLocation() - may have zero for JRE classes.

+3
source

Java-. , ASM, . ASM,

getClassLoader()
  .getResourceAsStream(ClassLoaderTest.class.getName().replace('.', '/') + ".class")

, , ( ).

ProtectionDomain, , , ClassLoader::getResource, ClassLoader, .

+1

All Articles