Thursday, June 20, 2013

How to access getClass() in static method?

In order to read a file which have been pack into JAR, usually this is what I did:
    class MyClass {
       private void readFromFile() {
          getClass().getClassLoader().getResourceAsStream("file_path");
       }
    }
Somehow this will only work only if it is an instance object. What if I’m reading the file from a static method? The code below shows the solution:
    class MyClass {
       private static void readFromFile() {
          MyClass.class.getClassLoader().getResourceAsStream("file_path");
       }
    }

No comments: