Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to check if a class is a local class in Java

Ravi

A class declared within another class is known as a nested class. A non-static nested class is known as an inner class or a local class.

Note: We can refer to What is an inner class in Java? to learn more about inner or local classes.

The isLocalClass() method

The isLocalClass() method in Java checks whether a class is a local class.

Syntax

The syntax for the method is as follows:

public boolean isLocalClass()

Parameters

The method doesn’t take any parameters.

Returns

This method returns a Boolean value. It returns true if the class is a local class. Otherwise, it returns false.

Coding example

import java.util.Arrays;

public class Main {

    public static void main(String[] args){

        class LocalInnerClass{
            void print(){
                System.out.println("I'm a local class/local inner class");
            }
        }

        LocalInnerClass localInnerClassObject = new LocalInnerClass();
        System.out.printf("Is %s a local class - %s", localInnerClassObject, localInnerClassObject.getClass().isLocalClass());
        System.out.println();
        
        Class<?> arraysClass = Arrays.class;
        System.out.printf("Is %s a local class - %s", arraysClass, arraysClass.isLocalClass());
    }
}
Using the isLocalClass() method

Code explanation

  • Line 1: We import the Arrays class.
  • Lines 7 to 11: We create a local inner class named LocalInnerClass. We define it with print() method that prints a string.
  • Line 13: We create an instance of LocalInnerClass named localInnerClassObject.
  • Line 14: We use the isLocalClass() method to the check if the localInnerClassObject is a local class.
  • Line 17: We retrieve the class object of the Arrays class using the .class property, and assign it to the arraysClass variable.
  • Line 18: We check if the arraysClass is a local class using the isLocalClass() method.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring