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


剛才在學習Java 使用properties類,遇到這樣的錯誤:

Cannot make a static reference to the non-static method getClass() from the type Object

以前使用過getClass,不曉得怎么用的,后來在stackoverflow看到同樣的問題

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:

publicstaticvoid 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?

牛人的回答是這樣的:

s 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:

classMyClass{
       publicstaticvoid 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 =newObject(){}.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...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM