当前位置: 代码迷 >> J2SE >> 怎么用class类的getSuperClass()获取父类名?我测试怎么不行啊
  详细解决方案

怎么用class类的getSuperClass()获取父类名?我测试怎么不行啊

热度:63   发布时间:2016-04-24 14:23:33.0
如何用class类的getSuperClass()获取父类名?我测试怎么不行啊?
如何用class类的getSuperClass()获取父类名?我测试怎么不行啊?
也许,是我的用法不对,请各位前辈指点一下.

class   A  
{
public   static   void   main(String[]   args)  
{
B   b=new   B();
System.out.println(b.getSuperClass());
}
}
class   B   extends   A
{
}


------解决方案--------------------
是通过Class类本身去获取运行期信息
参考:


//打印类继存层次树型结构
import java.util.*;
/**
* @author Ihavegotyou
* 打印类继存层次树型结构
*/
public class InheritRelation {
static Stack <Class> stack = new Stack <Class> ();
static Class fClass;
static Class getClassInheritRelation(final Class aClass) {
if (aClass != null) {
Class parentClass = aClass.getSuperclass();
if (parentClass != null)
stack.push(parentClass);
return getClassInheritRelation(parentClass);
} else
return null;
}

public InheritRelation(final Class aClass) {
super();
fClass = aClass;
getClassInheritRelation(aClass);
printInheritRelation();
}
public InheritRelation() {
new InheritRelation(this.getClass());
}
static void printInheritRelation() {
int i = 0;
while (!stack.isEmpty()) {
for (int j = 0; j <= i; j++)
System.out.print( '. ');
System.out.println(stack.peek().toString().substring(6));
stack.pop();
i++;
}
for (int j = 0; j <= i; j++)
System.out.print( '. ');
System.out.println(fClass.toString().substring(6));
System.out.println();
}
public static void main(String[] args) {
InheritRelation stack = new InheritRelation(new Stack().getClass());
InheritRelation hashmap=new InheritRelation(new HashMap().getClass());
try {
Class.forName( "InheritRelation ").newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}


------解决方案--------------------
class A
{
public static void main(String[] args)
{
//B b=new B();
System.out.println(B.class.getSuperclass());
}
}
class B extends A
{
}
------解决方案--------------------
System.out.println(b.getSuperClass());------>

System.out.println(b.getClass().getSuperclass());
getSuperclass()要用类来调用,不能单纯使用对象,注意大小写.
  相关解决方案