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?
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.
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.
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.
Method Local inner classes can't use a local variable of the outer method until that local variable is not declared as final.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With