Home » Java programming language

Java ClassLoader findClass() method with example

ClassLoader Class findClass() method: Here, we are going to learn about the findClass() method of ClassLoader Class with its syntax and example.
Submitted by Preeti Jain, on November 26, 2019

ClassLoader Class findClass() method

  • findClass() method is available in java.lang package.
  • findClass() method is used to find the class with the given binary class name.
  • findClass() 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.
  • findClass() method may throw an exception at the time of finding the class.
    ClassNotFoundException: This exception may throw when the given class does not exist.

Syntax:

    protected Class findClass(String class_name);

Parameter(s):

  • String class_name – represents the binary name of the class.

Return value:

The return type of this method is Class, it returns an object "Class".

Example:

// Java program to demonstrate the example 
// of Class findClass(String class_name) method of ClassLoader 

class FindClass extends ClassLoader {
    // Override findClass() of ClassLoader
    protected Class findClass(String name) throws ClassNotFoundException {
        if (name.equals("java.lang.String")) {}
        return getSystemClassLoader().loadClass(name);
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        // Creating an instance of FindClass
        FindClass fc = new FindClass();

        // we are finding the class java.lang.String and it returns
        // it already exists in Java
        Class cl = fc.findClass("java.lang.String");
        System.out.println("Class Found: " + cl.getName());
    }
}

Output

Class Found: java.lang.String


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.