Java reflection also dealing with inheritance concepts. You can get the direct interfaces and direct super class of a class by using method getInterfaces()
and getSuperclass()
of java.lang.Class
object.
getInterfaces()
will returns an array ofClass
objects that represent the direct super interfaces of the targetClass
object.getSuperclass()
will returns theClass
object representing the direct super class of the targetClass
object ornull
if the target representsObject
class, an interface, a primitive type, or void.
package org.kodejava.lang.reflect;
import javax.swing.*;
import java.util.Date;
public class GetSuperClassDemo {
public static void main(String[] args) {
GetSuperClassDemo.get(String.class);
GetSuperClassDemo.get(Date.class);
GetSuperClassDemo.get(JButton.class);
GetSuperClassDemo.get(Timer.class);
}
public static void get(Class<?> clazz) {
// Gets array of direct interface of clazz object
Class<?>[] interfaces = clazz.getInterfaces();
System.out.format("Direct Interfaces of %s:%n",
clazz.getName());
for (Class<?> clz : interfaces) {
System.out.println(clz.getName());
}
// Gets direct superclass of clazz object
Class<?> superclz = clazz.getSuperclass();
System.out.format("Direct Superclass of %s: is %s %n",
clazz.getName(), superclz.getName());
System.out.println("====================================");
}
}
Here is the result of the code snippet:
Direct Interfaces of java.lang.String:
java.io.Serializable
java.lang.Comparable
java.lang.CharSequence
Direct Superclass of java.lang.String: is java.lang.Object
====================================
Direct Interfaces of java.util.Date:
java.io.Serializable
java.lang.Cloneable
java.lang.Comparable
Direct Superclass of java.util.Date: is java.lang.Object
====================================
Direct Interfaces of javax.swing.JButton:
javax.accessibility.Accessible
Direct Superclass of javax.swing.JButton: is javax.swing.AbstractButton
====================================
Direct Interfaces of javax.swing.Timer:
java.io.Serializable
Direct Superclass of javax.swing.Timer: is java.lang.Object
====================================
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024