0

i have problem with the "getClass", the eclipse writing this messeage: "cannot make a static reference to the non-static method getClass() from the type Object"

this is the code:

 public static void main(String[] args) {
    JFrame f = new JFrame();
    File path = new File(getClass().getResource("/resources/image.jpg").getFile());
    BufferedImage image = ImageIO.read(path);

thank you!

efraim gavrieli
  • 17
  • 1
  • 1
  • 5
  • You are using getClass() - which is a public non-static method in the class that main is in. If you want to get getClass() - you need to first create an instance of this class, and call it on it. – Worthless Dec 05 '18 at 22:09
  • 2
    YourClass.class.getResource(...) – JB Nizet Dec 05 '18 at 22:09
  • @leonardkraemer: The dupe doesn't answer this specific problem an doesn't equip anyone to be able to answer it, unfortunately. – Makoto Dec 05 '18 at 22:22
  • @Makoto it should be https://stackoverflow.com/questions/8275499/how-to-call-getclass-from-a-static-method-in-java nevertheless it is 2 seconds of googling. I cant raise the flag again for the new dupe :/ Nevertheless the linked dupe educates about the reason for the error, which should help in the long run. – leonardkraemer Dec 05 '18 at 22:44
  • @leonardkraemer: Hopefully then you'll be suggesting better duplicates in the future with a bit more time to Google for them? :) – Makoto Dec 05 '18 at 22:57
  • @Makoto I'll cange my process looking for dupes. Unfortunately the dupes stackoverflow suggests (it was actually the top suggestion) are usually not of the same quality as googles if you copy paste the actual error message. :/ ty for marking it btw – leonardkraemer Dec 05 '18 at 23:08

3 Answers3

4

(If your class name is Main then) use Main.class.getResource instead of this.getClass.getResource

Read this for more details.

Lavish Kothari
  • 2,211
  • 21
  • 29
1

A static method belongs to the class.

A non-static method belongs to an instance of the class.

when you call getResource(), it isn't associated with any instance.

do something like

Main.class.getResource("images/pic.png")

you can find more information about static at here

PPCC
  • 189
  • 1
  • 5
  • 12
0

The static key word means the function "main" in this case is bound to the class itself, therefore you cannot call a method that is not static like this "getClass()" because then that would be the same as saying "this.getClass()" but this can't refer to any object since you are calling getClass in a static method. Hence why you have to reference the class itself inside the static method saying MainClass.class.getResource()

chinloyal
  • 1,023
  • 14
  • 42