Java 如何使用 getClass().getSuperclass() 获取父类名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20758550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get parent class name using getClass().getSuperclass()?
提问by Sivakumar M
I am trying to get the parent class name using
我正在尝试使用
public class ClassA extends Draw{
public ClassA(){
super();
}
.....
}
public class ClassC {
public getParent(Object a_class)
{
String superClass= a_class.getClass().getSuperclass().toString();
}
}
I have got the following error
我有以下错误
Exception in thread "main" java.lang.StackOverflowError
at Draw.<init>(Draw.java:2)
at ClassA.<init>(ClassA.java:2)
at ClassA.<init>(ClassA.java:5)
at ClassA.<init>(ClassA.java:5)
at ClassA.<init>(ClassA.java:5)
at ClassA.<init>(ClassA.java:5)
How to get the parent class Name I need a parent Class name How to get
如何获取父类名称 我需要一个父类名称 如何获取
回答by Elliott Frisch
I think you just want
我想你只是想要
super.getClass().getName();
or possibly
或者可能
super.getClass().getCanonicalName();
or, you could use
或者,你可以使用
this.getClass().getSuperclass().getName(); // <-- or getCanonicalName()
回答by Tobias
Use Class.getName()
:
String superClass = a_class.getClass().getSuperclass().getName();
To get just the name and not the package name, use Class.getSimpleName()
:
要仅获取名称而不是包名称,请使用Class.getSimpleName()
:
String superClass = a_class.getClass().getSuperclass().getSimpleName();
However, a_class
is already a Class
instance so you might want to use a_class.getSuperclass()
instead.
但是,a_class
已经是一个Class
实例,因此您可能想a_class.getSuperclass()
改用它。
回答by Alok
super.getClass().getName(); or
yourClass.getClass().getSuperclass().getName();
should work fine
应该工作正常