Unwanted import added by compiler

38 views Asked by At

I need the same code to work on different servers with different libraries.

So for example serverB contains libraryB. ClassB while serverA doesn't.

To make the code work on both servers I do not import the class explicitly but I declare it only when needed. For example:

If(serverB) {
   libraryB.ClassB foo = new libraryB. ClassB();

   foo.doSomething();
}else{
   whatever();
}

This usually works for me but now I installed my code on new servers and I get a NoClassFoundException. I decompile my class and the library is imported. Why? Can I avoid it?

Thanks

1

There are 1 answers

3
Ralf Kleberhoff On

Importing some class from a package has nothing to do with trying to locate that class at runtime. Whenever the JVM detects that a class like ClassB is needed, it will try to locate and load that class.

The exact specification when this will happen has some complexities, but it makes no difference whether you wrote the fully qualified libraryB.ClassB or the abbreviated ClassB and an import statement. And locating that class will surely happen before the JVM even tries to execute code that contains a reference to the class (like the code snippet you showed us).

Don't be mislead by the decompilation containing an import statement. You can try for yourself and compare two versions of your code, one written with import, and the other with fully qualified classname. The results will be the same. It's just a convenience of the decompiler preferring short classnames, so it always adds the relevant import statements (as long as that doesn't cause name collisions).

It's hard to understand why code like yours ever ran without throwing that error.