The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.lang  [58 examples] > Classes  [11 examples]

e67. Determining from Where a Class Was Loaded

    // Get the location of this class
    Class cls = this.getClass();
    ProtectionDomain pDomain = cls.getProtectionDomain();
    CodeSource cSource = pDomain.getCodeSource();
    URL loc = cSource.getLocation();  // file:/c:/almanac14/examples/
It is not possible to determine the location of classes loaded by the system class loader in the same way since the class' code source is null. The only other method is to use the -verbose option on the java command. This causes the Java virtual machine to print a message every time a class is loaded.
    > java -verbose MyApp

Here's a sample of the output:
    [Opened c:\jdk1.4\jre\lib\rt.jar]
    [Opened c:\jdk1.4\jre\lib\sunrsasign.jar]
    [Opened c:\jdk1.4\jre\lib\jsse.jar]
    [Opened c:\jdk1.4\jre\lib\jce.jar]
    [Opened c:\jdk1.4\jre\lib\charsets.jar]
    [Loaded java.lang.Object from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.io.Serializable from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.lang.Comparable from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.lang.CharSequence from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.lang.String from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.lang.Class from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.lang.Cloneable from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.lang.ClassLoader from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.lang.System from c:\jdk1.4\jre\lib\rt.jar]
    [Loaded java.lang.Throwable from c:\jdk1.4\jre\lib\rt.jar]

 Related Examples
e59. Getting a Class Object
e60. Getting the Name of a Class Object
e61. Determining If a Class Object Represents a Class or Interface
e62. Getting the Superclass of an Object
e63. Getting the Superclass of a Class Object
e64. Listing the Interfaces That a Class Implements
e65. Listing the Interfaces That an Interface Extends
e66. Getting the Package of a Class
e68. Loading a Class That Is Not on the Classpath
e69. Dynamically Reloading a Modified Class

See also: Arrays    Assertions    Commands    Numbers    Objects    Strings    System Properties    Threads   


© 2002 Addison-Wesley.