class
Check where a class was loaded from
This is an example of how to check where a class was loaded from. To check where a class was loaded from we have created a class, CheckWhereAClassWasLoadedFrom
. It has a method void getLocation()
that gets the location of the class. The steps of the method are described below:
- It gets the runtime class of this Object using
getClass()
API method of Object for the specific instance. - It gets the ProtectionDomain that encapsulates the characteristics of a domain, which encloses a set of classes whose instances are granted a set of permissions when being executed on behalf of a given set of Principals, using
getProtectionDomain()
API method of Class. - It gets the CodeSource to encapsulate not only the location (URL) but also the certificate chains that were used to verify signed code originating from that location, with
getCodeSource()
API method of ProtectionDomain. - Then it gets the URL associated with this CodeSource, with
getLocation()
API method of CodeSource.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; public class CheckWhereAClassWasLoadedFrom { public static void main(String[] args) { new CheckWhereAClassWasLoadedFrom().getLocation(); } private void getLocation() { // get the runtime class of this Object Class<?> cls = this.getClass(); // get the ProtectionDomain, a class that encapsulates the characteristics of a domain, // which encloses a set of classes whose instances are granted a set // of permissions when being executed on behalf of a given set of Principals ProtectionDomain pDomain = cls.getProtectionDomain(); // get the CodeSource, a class extends the concept of a codebase to // encapsulate not only the location (URL) but also the certificate chains // that were used to verify signed code originating from that location CodeSource cSource = pDomain.getCodeSource(); // get the location associated with this CodeSource URL location = cSource.getLocation(); System.out.println("Location: " + location); } }
Output:
Location: file:/C:/workspace/MyProject/bin/
This was an example of how to check where a class was loaded from in Java.