How to know from where a Class was loaded in Java
Published: February 8, 2010 , Updated: January 20, 2010 , Author: mkyong
Here’s a tip to demonstrate how to know from where a Java Class was loaded in Java.
Java Example
Here’s an example to load a Java class called “Address “, package in “com.mkyong.io“, and print out the location from where this class was loaded.
import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; public class App{ public static void main(String[] args) { try{ Class cls = Class.forName("com.mkyong.io.Address"); ProtectionDomain pd = cls.getProtectionDomain(); CodeSource cs = pd.getCodeSource(); URL url = cs.getLocation(); System.out.println(url.getFile()); }catch(Exception ex){ ex.printStackTrace(); } } }
Output
/E:/workspace/HibernateExample/target/classes/
The Java class “Address” is located at “E:/workspace/HibernateExample/target/classes/com/mkyong/io/Address.class”
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~