In this section, you will learn how to get the class location.
Java Get Class Location
In this section, you will learn how to get the class location. For this, we have used the classes URL and ClassLoader. The class ClassLoader is responsible to load the classes. The method loader.getResource(classLocation) returns the location of the class.
import java.net.URL; public final class GetClassLocation { private GetClassLocation() { super(); } public static final void main(final String[] args) throws Throwable { final URL location; final String classLocation = GetClassLocation.class.getName().replace('.', '/') + ".class"; final ClassLoader loader = GetClassLocation.class.getClassLoader(); if (loader == null) { System.out.println("Cannot load the class"); } else { location = loader.getResource(classLocation); System.out.println("Class "+location); } } } |
Output will be displayed as: