Get Class name from within a method
I would like to reference a Class's name within a method. In the following example, I would like TestSuite to be printed out. I can put CarsTestSuite.class.getName()
, but I'd like to use the method to get the class name so that I 开发者_运维知识库never have to edit it. The solution will find the method's class instead of myself filling it in.
public class TestSuite extends TestCase {
public static void testOne() {
System.out.println(<want TestSuite to be here>);
this.getClass().getCanonicalName()
or this.getClass().getName()
.
Your method is static so this won't work. Does it need to be static?
You can't do that in a static method. In a non-static method you can call getClass()
, but in a static method the method's class never changes, and thus the class (and thus its name) can only be accessed statically, and in TestSuite.class
.
I do need it to be static because in another class I call that class. So if I do
TestSuite.testOne();
in another class, it will not let me do so unless I have testOne() declared as static.
You can use the fact that the stacktrace of exception consists information about current class and method in first element. I used such construct when I wanted to log current class name:
new Exception().getStackTrace()[0].getClassName()
In the same way you can retrieve also current method name (StackTraceElement.getMethodName()
)
精彩评论