Note that there are some explanatory texts on larger screens.

plurals
  1. POStrange Java Class-Path/Class-Loader behaviour
    text
    copied!<p>I have a very strange Java class path behaviour when loading a class file which references other classes which are not available at runtime.</p> <p>Loading a class which has a (at runtime untouched method) which calls a constructor of another class with a parameter that is casted to a class which inherits the class of the parameter causes a class not found exception of the paramter class if only the class to load but no other classes referenced in methods of that class is in class path.</p> <p>I am using following java:</p> <pre><code>java version "1.6.0_18" Java(TM) SE Runtime Environment (build 1.6.0_18-b07) Java HotSpot(TM) 64-Bit Server VM (build 16.0-b13, mixed mode) (Windows Server 2008 R2) </code></pre> <p>Here is a sample:</p> <pre><code>public class A { public static void main(String[] args) { System.out.println("it works"); } public void foo() { new B((D)null); } } public class B { public B(C c) { } } public class C { } public class D extends C { } </code></pre> <p>Now i compile the classes, and if i execute the class A with all class files in the class path, it yields "it works".</p> <p>If i remove all classes excepet class A from the class path, following error occurs:</p> <pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: C Caused by: java.lang.ClassNotFoundException: C at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Could not find the main class: A. Program will exit. </code></pre> <p>although class C should never be needed at runtime.</p> <p>Following constellation works (replaced "new B((D)null)" in class A):</p> <pre><code>public class A { public static void main(String[] args) { System.out.println("it works"); } public void foo() { D d = (D)null; d.toString(); B b = (B)null; b.toString(); new B(null); } } public class B { public B(C c) { } } public class C { } public class D extends C { } </code></pre> <p>Following constellation also works (cast to C instead of D; C does not inherit any class)</p> <pre><code>public class A { public static void main(String[] args) { System.out.println("it works"); } public void foo() { new B((C)null); } } public class B { public B(C c) { } } public class C { } public class D extends C { } </code></pre> <p>Is this an expected behaviour or a Java bug?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload