可以使用java.lang.Class.getSuperclass()方法获得任何实体的直接超类信息,例如对象,类,原始类型,接口等。
演示此的程序如下所示-
package Test; import java.lang.*; class Class1{ } class Class2 extends Class1{ } public class Demo { public static void main(String args[]) { Class1 obj1 = new Class1(); Class2 obj2 = new Class2(); Class c; c = obj2.getClass(); System.out.println("The class of object obj2 is: " + c.getName()); c = c.getSuperclass(); System.out.println("The super class of object obj2 = " + c.getName()); } }
输出结果
The class of object obj2 is: Test.Class2 The super class of object obj2 = Test.Class1
现在让我们了解上面的程序。
首先定义类class1和class2。演示这的代码片段如下-
class Class1{ } class Class2 extends Class1{ }
在该方法中main()
,定义了类class1和class2的对象obj1和obj2。然后getClass()
用于获取对象obj2的类,并getSuperclass()
用于获取对象obj2的超类。演示这的代码片段如下-
Class1 obj1 = new Class1(); Class2 obj2 = new Class2(); Class c; c = obj2.getClass(); System.out.println("The class type of object obj2 is: " + c.getName()); c = c.getSuperclass(); System.out.println("The super class of object obj2 = " + c.getName());