Close

Java Reflection - Class.getEnclosingClass() Examples

Code Snippets Java Reflection Java Java API 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public Class<?> getEnclosingClass()
                           throws SecurityException
Returns:
the immediately enclosing class of the underlying class


Examples


package com.logicbig.example.clazz;

public class GetEnclosingClassExample {

public static void main(String... args) {
Class<MyClass> c = MyClass.class;
Class<?> enclosingClass = c.getEnclosingClass();
System.out.println(enclosingClass);
}

private static class MyClass {}
}

Output

class com.logicbig.example.clazz.GetEnclosingClassExample




package com.logicbig.example.clazz;

public class GetEnclosingClassExample2 {

public static void main(String... args) {
Class<GetEnclosingClassExample2> c = GetEnclosingClassExample2.class;
System.out.println(c.getEnclosingClass());
}
}

Output

null




This example also shows difference between getEnclosingClass() and getDeclaringClass() for an anonymous class

package com.logicbig.example.clazz;

public class GetEnclosingClassExample3 {

public static void main(String... args) {
//an anonymous class
new Object() {
{
Class<? extends Object> c = this.getClass();
System.out.println("enclosing: " + c.getEnclosingClass());
System.out.println("declaring: " + c.getDeclaringClass());
}
};

}
}

Output

enclosing: class com.logicbig.example.clazz.GetEnclosingClassExample3
declaring: null




package com.logicbig.example.clazz;

import java.io.Serializable;

public class GetEnclosingClassExample4 {

public static void main(String... args) {
//another anonymous class
Serializable s = new Serializable() {};
Class<? extends Serializable> c = s.getClass();
System.out.println(c.getEnclosingClass());
System.out.println(c.getDeclaringClass());
}
}

Output

class com.logicbig.example.clazz.GetEnclosingClassExample4
null




See Also