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

xiongchenyan 2007-07-23 08:42:32
如何用class类的getSuperClass()获取父类名?我测试怎么不行啊?
也许,是我的用法不对,请各位前辈指点一下.

class A
{
public static void main(String[] args)
{
B b=new B();
System.out.println(b.getSuperClass());
}
}
class B extends A
{
}
...全文
932 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
易生一世 2012-03-27
  • 打赏
  • 举报
回复
有意思,学习了
clevercong 2007-07-23
  • 打赏
  • 举报
回复
学习了,学习了。
dragon_up 2007-07-23
  • 打赏
  • 举报
回复
System.out.println(b.getSuperClass());------>

System.out.println(b.getClass().getSuperclass());
getSuperclass()要用类来调用,不能单纯使用对象,注意大小写.
liuxia1219 2007-07-23
  • 打赏
  • 举报
回复
class A
{
public static void main(String[] args)
{
//B b=new B();
System.out.println(B.class.getSuperclass());
}
}
class B extends A
{
}
xiongchenyan 2007-07-23
  • 打赏
  • 举报
回复
不好意思,我太笨了,看不懂那么复杂的,请您把我上面的这个程序修改一下,用
class 类的getSuperClass()方法输出B类的父类,谢谢.
IhaveGotYou 2007-07-23
  • 打赏
  • 举报
回复
是通过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();
}
}
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧