Java Reflection - Class.getDeclaringClass() Examples

Code Snippets Java Reflection Java 


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<?> getDeclaringClass()
                           throws SecurityException
Returns:
the declaring class for this class


Examples


package com.logicbig.example.clazz;

public class GetDeclaringClassExample {

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

private static class MyClass {}
}

Output

class com.logicbig.example.clazz.GetDeclaringClassExample




package com.logicbig.example.clazz;

public class GetDeclaringClassExample2 {

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

Output

null




getEnclosingClass() returns non-null value.

package com.logicbig.example.clazz;

import java.io.Serializable;

public class GetDeclaringClassExample3 {

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

Serializable s = new Serializable() {};
System.out.println(s.getClass().getDeclaringClass());
}
}

Output

null
null




package com.logicbig.example.clazz;

public class GetDeclaringClassExample4 {

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

private static class MyClass {
private static interface AnInnerInterface {}
}
}

Output

class com.logicbig.example.clazz.GetDeclaringClassExample4$MyClass




See Also