How to get Java class name from static code

July 15th, 2009 | by Sean |

I thought of one way to do this, but checked Google first to see if there was an easier, more obvious way. Real Gagnon has a method at his site which is similar to the way I thought I could do it, but no less obscure or easy!

Here’s my code, in case it comes in handy for you:

System.out.println(Thread.currentThread()
    .getStackTrace()[1].getClassName());

The first (zeroth!) thread in the stack trace is ‘java.lang.Thread’.

It’s a pity Sun didn’t use the reserved word ‘class’ as the static counterpart to ‘this’. That way it should have been possible to get the name as “class.getName()”, which would have been neat. I’m sure there must be a good reason. Is there?

Post a Comment