Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get getclass().getResource() from a static context?

I have a function where I am trying to load a file to a URL object, because the example project said so.

public class SecureFTP {      public static void main(String[] args) throws IOException , ClassNotFoundException, SQLException , JSchException, SftpException{         File file = new File("/home/xxxxx/.ssh/authorized_keys");         URL keyFileURL = this.getClass().getClassLoader().getResource(file); 

I tried using SecureFTP.class.getResource, but it still could not compile it.

I am fairly new to Java, so I know I am doing something wrong.

like image 378
roymustang86 Avatar asked Dec 02 '11 20:12

roymustang86


People also ask

How do you use this in static context?

But static contexts(methods and blocks) doesn't have any instance they belong to the class. In a simple sense, to use “this” the method should be invoked by an object, which is not always necessary with static methods. Therefore, you cannot use this keyword from a static method.

Can't be referenced from a static context?

And if no class instance is created, the non-static variable is never initialized and there is no value to reference. For the same reasons, a non-static method cannot be referenced from a static context, either, as the compiler cannot tell which particular object the non-static member belongs to.

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 main method is a static method, so trying to access this (= the current Object) will not work. You can replace that line by

URL keyFileURL = SecureFTP.class.getClassLoader().getResource("/home/xxxxx/.ssh/authorized_keys"); 
like image 79
Robin Avatar answered Sep 18 '22 15:09

Robin