Home »
Java programming language
Java ClassLoader getResource() method with example
ClassLoader Class getResource() method: Here, we are going to learn about the getResource() method of ClassLoader Class with its syntax and example.
Submitted by Preeti Jain, on November 28, 2019
ClassLoader Class getResource() method
- getResource() method is available in java.lang package.
- getResource() method is used to return the resource with the given resource name in URL objects.
- getResource() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- getResource() method does not throw an exception at the time of returning resource.
Syntax:
public URL getResource(String resource_name);
Parameter(s):
- String resource_name – represents the name of the resource.
Return value:
The return type of this method is URL, it returns URL object for scanning the resource otherwise it returns null when the given resource does not exist.
Example:
// Java program to demonstrate the example
// of URL getResource(String resource_name)
// method of ClassLoader
import java.net.*;
public class GetResourceOfClassLoader {
public static void main(String args[]) throws Exception {
// It loads the class
Class cl = Class.forName("GetResourceOfClassLoader");
// It returns the class loader associated with
// the given class
ClassLoader loader = cl.getClassLoader();
// Display Loader Class
System.out.println("Loader Class : ");
System.out.println(loader.getClass());
System.out.println();
// It returns the resource associates with this Class
// GetParentOfClassLoader
URL res_url = loader.getResource("E://Programs//getProperties().doc");
// Display Resource
System.out.println("Class Resource : ");
System.out.println(res_url);
}
}
Output
Loader Class :
class sun.misc.Launcher$AppClassLoader
Class Resource :
file:/E:/Programs/getProperties().doc