Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call getClass() from a static method in Java?

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?

like image 281
Rama Avatar asked Nov 26 '11 00:11

Rama


People also ask

What is the use of getClass () in Java?

The Java Object getClass() method returns the class name of the object.

How do you solve Cannot make a static reference to the non-static method?

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.


1 Answers

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.

like image 126
Mark Peters Avatar answered Sep 17 '22 14:09

Mark Peters