Local Inner Classes are classes declared inside a block. These classes are only visible inside the block. So, You need to instantiate the class within the block. Sometimes, this block can be for loop or if-else clause. These classes can access the fields of a class enclosing it. The local inner class must be instantiated in the block they are defined in.
We will discuss using the below approaches how to check if a given class is a Local Inner Class.
- To check whether the class is a local inner class, java.lang.Class provides a method called isLocalClass().
- This method returns true if the given class is a local class and false otherwise. Note that “isLocalClass()” is defined in java.lang.Class class. So, you need to first call the “getClass()” method of the object.
- This method returns the Class instance representing the class of the object. See the following code —
Is inner a local class object? :true
- This approach is about checking the canonical name of the class and then deciding whether it is a local class or not.
- The getCanonicalName() method defined in java.lang.
- Class class, returns the canonical name of the class in as a string.
- For example, if the name of a class represented by the java.lang.Class object, is “GFG”, then the “getCanonicalName()” method returns “GFG”.
GFG gfg = new GFG(); System.out.println(gfg.getClass().getCanonicalName());
If we run the above code in a program, then the output received will be:
Note: A.) If there is a package name, then the output will be “package-name.GFG”.
- But this is not the case for local, anonymous classes.
- If the class is a member class, say, “GFG” is a member class of “GeeksForGeeks”, then “getCanonicalName()” will return “GeeksForGeeks.GFG”(in the form “(Name_of_Enclosing_Class).(Name_of_this_Class)”).
B.) If the class is an anonymous class inside a class (say, “GFG”) then the “getCanonicalName()” method returns null because it does not have a canonical name.
C.) If the class is a local inner class, suppose, “GFG” is a local class inside “GeeksForGeeks”, then also “getCanonicalName()” will return null. Because, it does not have a canonical name
Canonical Name of the class of gfg:null Canonical Name of the class of geeks:null
Using this canonical name, you can achieve the given task. Check the following code:
Is gfg a local class instance?: true
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.