3

There is the following PMD rule:

Use Proper Class Loader (Critical)

In J2EE getClassLoader() might not work as expected. Use Thread.currentThread().getContextClassLoader() instead.

Can somewhat explain more what they are thinking of? What exactly means "J2EE" environment here?

Community
  • 1
  • 1
igr
  • 10,199
  • 13
  • 65
  • 111

1 Answers1

1

J2EE environment refers to the Java Enterprise Edition. Here, you do not run your program as a standalone application on the JVM, but instead, you let the JEE Application Server (e.g. Glassfish or Tomcat) to run it for you.

Application Servers provide a lot of different ways to run your program, for example they offer concurrent and distributed execution. AppServers play with classloaders, sometimes there is a hierarchy, for example the EAR (Enterprise ARchive) has one, and a WAR (Web ARchive) inside the EAR has a different one. Because of this it is not ensured you will always get the right ClassLoader with a getClassLoader() call. With Thread.currentThread().getContextClassLoader() you will always get the ClassLoader that loaded your app.

(Note: This is not entirely true, some applications make trick with ContextClassLoader (like Spring, OSGi). Still, this is the best way to get your proper ClassLoader).

Csuki
  • 1,297
  • 8
  • 21
  • "get the right ClassLoader" - this part is unclear. if I say: `ref.getClass().getClassLoader()`, i should get the class loader that loaded this class, right? How this can be changed? I am not talking about the classloader that loaded my app; as my class may be loaded by different classloader. – igr Jan 14 '16 at 14:26
  • Maybe this post clarifies it: http://stackoverflow.com/questions/1771679/difference-between-threads-context-class-loader-and-normal-classloader – Csuki Jan 14 '16 at 16:21
  • Hm, i do understand the difference, maybe I need to clarify myself. If I do `ref.getClass().getClassLoader()` - i should always get the class loader that loaded class of `ref`. And this can not change, right? This may or may not be the same as context CL, but that is on me to handle if I need. Sometimes I want this, sometimes i don't. So I am puzzled why PMD would warn about this anyway - it sounds as a rule that you should use in jee environment - and wonder if there is something more that i dont see. – igr Jan 14 '16 at 16:57