Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen creating a reference for an object where that class is loaded from?
    text
    copied!<p>When doing some sample coding with Java I came across ClassCastException, from where I cast the object to StaticClass. Can anyone explain what has happened here?</p> <pre><code>public void test5() throws Exception { System.out.println(StaticClass.obj); Object newInstance = ClassLoader.getSystemClassLoader().loadClass("com.StaticClass").newInstance(); System.out.println(newInstance.getClass().getDeclaredField("obj").get(newInstance)); Object newInstance2 = new ILoader().loadClass("com//StaticClass.class").newInstance(); System.out.println(newInstance2.getClass().getDeclaredField("obj").get(newInstance2)); StaticClass s = (StaticClass)newInstance2; System.out.println(s.obj); System.out.println(newInstance.getClass().getClassLoader()); System.out.println(newInstance2.getClass().getClassLoader()); } </code></pre> <hr> <pre><code>package com; public class StaticClass { public static final Object obj = new Object(); } </code></pre> <hr> <pre><code>package com; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ILoader extends ClassLoader { public ILoader() { super(null); } @Override protected Class&lt;?&gt; findClass(String name) throws ClassNotFoundException { File file = new File(name); byte[] bytes = new byte[(int)file.length()]; try { new FileInputStream(file).read(bytes); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return super.defineClass("com.StaticClass",bytes, 0, bytes.length); } } </code></pre> <hr> <p>output which was given by last System.out when the casting part of the code not existed is as below.</p> <pre><code>sun.misc.Launcher$AppClassLoader@133056f com.ILoader@1ac3c08 </code></pre>
 

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