Home » Java programming language

Java Class class getDeclaredClasses() method with example

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

Class class getDeclaredClasses() method

  • getDeclaredClasses() method is available in java.lang package.
  • getDeclaredClasses() method is used to return an array of Class objects that reflects private, protected, public, and default defined by the class but it does not include child classes or interfaces.
  • getDeclaredClasses() 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.
  • getDeclaredClasses() method may throw a SecurityException at the time of returning an array of Class objects.
    SecurityException: In this exception, it may raise when the security manager exists.

Syntax:

    public Class[] getDeclaredClasses ();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is Class, it returns an array of Class object denoting the defined member of this Class.

Note:

  • When the class does not declare classes or interfaces as member, 0 is returned.
  • When the class reflects primitive or void type or an array type, 0 is returned.

Example:

// Java program to demonstrate the example 
// of Class [] getDeclaredClasses () method of Class 

public class GetDeclaredClassesOfClass {
    public static void main(String[] args) throws Exception {
        // It returns the Class object with the given class name
        Class cl = Class.forName("java.lang.String");

        // It returns an array of Classes 
        // that denotes the private, protected, public and default 
        // classes of the class String
        Class[] cl_array = cl.getDeclaredClasses();

        // Traversing String class
        for (int i = 1; i < cl_array.length; ++i) {
            System.out.print(" String Declared Classes: ");
            System.out.println(cl_array[i].getName());
        }
    }
}

Output

Declared Classes:java.lang.String$CaseInsensitiveComparator


Comments and Discussions!

Load comments ↻





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