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!

6
  • 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. Commented Dec 5, 2018 at 22:09
  • 2
    YourClass.class.getResource(...) Commented Dec 5, 2018 at 22:09
  • @leonardkraemer: The dupe doesn't answer this specific problem an doesn't equip anyone to be able to answer it, unfortunately. Commented Dec 5, 2018 at 22:22
  • @Makoto it should be stackoverflow.com/questions/8275499/… 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. Commented Dec 5, 2018 at 22:44
  • @leonardkraemer: Hopefully then you'll be suggesting better duplicates in the future with a bit more time to Google for them? :) Commented Dec 5, 2018 at 22:57

3 Answers 3

4

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

Read this for more details.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.