The Answer
Just use TheClassName.class
instead of getClass()
.
Declaring Loggers
Since this gets so much attention for a specific usecase–to provide an easy way to insert log declarations–I thought I’d add my thoughts on that. Log frameworks often expect the log to be constrained to a certain context, say a fully-qualified class name. So they are not copy-pastable without modification. Suggestions for paste-safe log declarations are provided in other answers, but they have downsides such as inflating bytecode or adding runtime introspection. I don’t recommend these. Copy-paste is an editor concern, so an editor solution is most appropriate.
In IntelliJ, I recommend adding a Live Template:
- Use “log” as the abbreviation
- Use
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger($CLASS$.class);
as the template text. - Click Edit Variables and add CLASS using the expression
className()
- Check the boxes to reformat and shorten FQ names.
- Change the context to Java: declaration.
Now if you type log<tab>
it’ll automatically expand to
private static final Logger logger = LoggerFactory.getLogger(ClassName.class);
And automatically reformat and optimize the imports for you.