I have a class that must have some static methods. Inside these static methods I need to call the method getClass() to make the following call:
public static void startMusic() { URL songPath = getClass().getClassLoader().getResource("background.midi"); }
However Eclipse tells me:
Cannot make a static reference to the non-static method getClass() from the type Object
What is the appropriate way to fix this compile time error?
The Java Object getClass() method returns the class name of the object.
The obvious solution to fix "Cannot make a static reference to the non-static method or a non-static field" error in Java is to create an instance of the class and then access the non-static members. That's all for this topic Fix Cannot make a static Reference to The Non-static Method Error.
Just use TheClassName.class
instead of getClass()
.
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:
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger($CLASS$.class);
as the template text. className()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With