Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the outer class object from an inner class object

In a nutshell, I'm trying to do the inverse of "classObject.getDeclaredClasses()".

I have a method that receives an object of type Class<? extends Object>. I want to figure out whether it is an inner class, and if it is, I want to access the surrounding class' object instance.

Is there a smart API for this, or am I forced to do some string manipulation and parsing?

like image 913
Henrik Paul Avatar asked Oct 29 '10 11:10

Henrik Paul


People also ask

When we create object of outer class the object of inner class is automatically created?

No inner class objects are automatically instantiated with an outer class object. If the inner class is static, then the static inner class can be instantiated without an outer class instance. Otherwise, the inner class object must be associated with an instance of the outer class.

How do you access the outer class variable in an inner static class?

Unlike inner class, a static nested class cannot access the member variables of the outer class. It is because the static nested class doesn't require you to create an instance of the outer class.

Can we access inner class from outer class or classes from another package?

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

Can inner class calling Outer method?

Method Local inner classes can't use a local variable of the outer method until that local variable is not declared as final.


2 Answers

You are looking for the Class.getDeclaringClass() method:

public Class getDeclaringClass()

If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class in which it was declared. This method returns null if this class or interface is not a member of any other class. If this Class object represents an array class, a primitive type, or void,then this method returns null.

Returns: the declaring class for this class

like image 166
Abhinav Sarkar Avatar answered Nov 15 '22 19:11

Abhinav Sarkar


Referencing the Outer Class Instance From the Inner Class Code

If inner class code needs a reference to the outer class instance that it is attached to, use the name of the outer class, a dot, and this

* remember that if there is no name conflict, there is no need for any special syntax
* for code in MyInner to obtain a reference to its MyOuter:

  MyOuter.this

static Inner Classes

An inner class may be marked as static

A static inner class my be instantiated without an instance of the outer class

* static members of the outer class are visible to the inner class, no matter what their access level
* non-static members of the outer class are not available, since there is not instance of the outer class to retrieve them from
like image 43
yash Avatar answered Nov 15 '22 20:11

yash