Main Tutorials

How to know from where a Class was loaded in Java

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
balakrishna gajam
11 years ago

good to know…