When Creating a Reference for an Object Where from where that class is Loaded?
Posted
by
asela38
on Stack Overflow
See other posts from Stack Overflow
or by asela38
Published on 2010-12-31T04:20:55Z
Indexed on
2010/12/31
4:54 UTC
Read the original article
Hit count: 195
java
|classloader
When doing some sample codings with Java I came crosss ClassCast Exception, from where I cast the object to StaticClass. Can any explaing the what has happened here.
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());
}
package com;
public class StaticClass {
public static final Object obj = new Object();
}
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<?> 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);
}
}
output which was given by last sysout's when the casting part of the code not existed is as belows.
sun.misc.Launcher$AppClassLoader@133056f
com.ILoader@1ac3c08
© Stack Overflow or respective owner