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.
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With