[英]How can I get the name of a class, with an static Method (not with Exception)
I have to write a method which can be called in any class to get the name of the class which is calling the method.我必须编写一个可以在任何类中调用的方法,以获取调用该方法的类的名称。 The return type should be Class
, so I can use it for another method.返回类型应该是Class
,所以我可以将它用于另一种方法。 So that is what I have right now, but I think its not a clean code.所以这就是我现在所拥有的,但我认为它不是一个干净的代码。 Maybe there is way to use也许有办法使用
public class Vlogger{
public static Class getInstance() throws ClassNotFoundException {
String className =new Exception().getStackTrace()[1].getClassName();
return Class.forName(className);
}
}
Unfortunately, there is no clean code for this task yet.不幸的是,这个任务还没有干净的代码。
Be prepared to replace it, when Java 9 has been released:准备好在Java 9发布后替换它:
public class Vlogger{
public static Class getInstance() {
return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
.getCallerClass();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.