Java如何获得直接的超类和类的接口?
Java反射还处理继承概念。可以使用的方法getInterfaces()和getSuperclass()获取类的直接接口和直接超类java.lang.Class类对象。
getInterfaces()将返回一个Class对象数组,这些对象代表目标Class对象的直接超级接口。
getSuperclass()将返回Class表示目标Class对象的直接超类的对象,或者null如果目标表示Object类,接口,原始类型或void,则返回该对象。
package org.nhooo.example.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) {
// 获取clazz对象的直接接口数组
Class[] interfaces = clazz.getInterfaces();
System.out.format("Direct Interfaces of %s:%n",
clazz.getName());
for (Class clz : interfaces) {
System.out.println(clz.getName());
}
// 获取clazz对象的直接超类
Class superclz = clazz.getSuperclass();
System.out.format("Direct Superclass of %s: is %s %n",
clazz.getName(), superclz.getName());
System.out.println("====================================");
}
}这是代码段的结果:
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 ====================================