0

Just curious that when will the below line fail?

this.getClass().getClassLoader();

ClassLoader will ALWAYS be found right ? is there any situation that the ClassLoader cannot be found ?

Seng Zhe
  • 613
  • 1
  • 11
  • 21
  • https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getClassLoader() - will fail due to permission issues or if this object represents a primitive type or void – Dana Jan 16 '17 at 04:12
  • 1
    Down-voted question for lack of research, since javadoc of [`getClassLoader()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getClassLoader--) documents *"when will the below line fail?"* – Andreas Jan 16 '17 at 04:37

1 Answers1

1

Take a look at the source code. This method throws only SecurityException when there is a SecurityManager and you are not permitted to access it.

public ClassLoader getClassLoader() {
        ClassLoader cl = getClassLoader0();
        if (cl == null)
            return null;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
        }
        return cl;
    }

And in case you are wondering what cl could be null. Here is an answer.

Community
  • 1
  • 1
bresai
  • 369
  • 5
  • 18
  • 1
    No need to look at the source code. Both the `null` value and the security check is well documented in the javadoc of [`getClassLoader()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getClassLoader--). The documentation is actually better, since it shows exactly what exception is thrown, which the shown source doesn't. It also explains what the `null` value *means*, which again the shown source doesn't. Always use javadoc as your first source of information about Java API methods. – Andreas Jan 16 '17 at 04:33