tags:

views:

64

answers:

4

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>);
+3  A: 

this.getClass().getCanonicalName() or this.getClass().getName().

Your method is static so this won't work. Does it need to be static?

Jonathon
No it doesn't need to be static and the above example: this.getClass().getName() worked. Thank you.
True_Blue
A: 

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.

Jherico
A: 

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.

True_Blue
A: 

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())

DixonD