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

JavaStatic Methods

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

As for the code example in the question, the standard solution is to reference the class explicitly by its name, and it is even possible to do without getClassLoader() call:

class MyClass {
  public static void startMusic() {
    URL songPath = MyClass.class.getResource("background.midi");
  }
}

This approach still has a back side that it is not very safe against copy/paste errors in case you need to replicate this code to a number of similar classes.

And as for the exact question in the headline, there is a trick posted in the adjacent thread:

Class currentClass = new Object() { }.getClass().getEnclosingClass();

It uses a nested anonymous Object subclass to get hold of the execution context. This trick has a benefit of being copy/paste safe...

Caution when using this in a Base Class that other classes inherit from:

It is also worth noting that if this snippet is shaped as a static method of some base class then currentClass value will always be a reference to that base class rather than to any subclass that may be using that method.

Solution 3 - Java

In Java7+ you can do this in static methods/fields:

MethodHandles.lookup().lookupClass()

Solution 4 - Java

I wrestled with this myself. A nice trick is to use use the current thread to get a ClassLoader when in a static context. This will work in a Hadoop MapReduce as well. Other methods work when running locally, but return a null InputStream when used in a MapReduce.

public static InputStream getResource(String resource) throws Exception {
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   InputStream is = cl.getResourceAsStream(resource);
   return is;
}

Solution 5 - Java

Simply use a class literal, i.e. NameOfClass.class

Solution 6 - Java

Try it

Thread.currentThread().getStackTrace()[1].getClassName()

Or

Thread.currentThread().getStackTrace()[2].getClassName()

Solution 7 - Java

getClass() method is defined in Object class with the following signature:

> public final Class getClass()

Since it is not defined as static, you can not call it within a static code block. See these answers for more information: Q1, Q2, Q3.

If you're in a static context, then you have to use the class literal expression to get the Class, so you basically have to do like:

> Foo.class

This type of expression is called Class Literals and they are explained in Java Language Specification Book as follows:

> A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a `.' and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.

You can also find information about this subject on API documentation for Class.

Solution 8 - Java

I had the same problem ! but to solve it just modify your code as following.

public static void startMusic() {
URL songPath = YouClassName.class.getClassLoader().getResource("background.midi");
}

this worked fine with me hope it will also work fine with you.

Solution 9 - Java

Suppose there is a Utility class, then sample code would be -

    URL url = Utility.class.getClassLoader().getResource("customLocation/".concat("abc.txt"));

CustomLocation - if any folder structure within resources otherwise remove this string literal.

Solution 10 - Java

Try something like this. It works for me. Logg (Class name)

    String level= "";

    Properties prop = new Properties();

    InputStream in =
            Logg.class.getResourceAsStream("resources\\config");

    if (in != null) {
        prop.load(in);
    } else {
        throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
    }

    level = prop.getProperty("Level");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRamaView Question on Stackoverflow
Solution 1 - JavaMark PetersView Answer on Stackoverflow
Solution 2 - JavaSergey UshakovView Answer on Stackoverflow
Solution 3 - JavaReinView Answer on Stackoverflow
Solution 4 - JavastarkadderView Answer on Stackoverflow
Solution 5 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 6 - JavaIshfaqView Answer on Stackoverflow
Solution 7 - JavamelihcelikView Answer on Stackoverflow
Solution 8 - Javauser14203853View Answer on Stackoverflow
Solution 9 - JavaPravind KumarView Answer on Stackoverflow
Solution 10 - JavaOliver Lagerbäck WestblomView Answer on Stackoverflow