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

roymustang86 picture roymustang86 · Dec 2, 2011 · Viewed 57.6k times · Source

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.

Answer

Robin picture Robin · Dec 2, 2011

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");