import java.io.IOException;
import java.io.InputStream;
/**
* 类加载器与instanceof演示
* */
public class ClassLoadTest {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
ClassLoader classLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException{
try {
String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
InputStream is = getClass().getResourceAsStream(fileName);
if(is == null){
return super.loadClass(name);
}
byte[] b = new byte[is.available()];
is.read(b);
return defineClass(name,b, 0, b.length);
} catch (IOException e) {
// TODO: handle exception
throw new ClassNotFoundException(name);
}
}
};
Object object = classLoader.loadClass("com.jvm.ch7.ClassLoadTest").newInstance();
System.out.println(object.getClass());
System.out.println(object instanceof com.jvm.ch7.ClassLoadTest);
}
}
类加载器
最新推荐文章于 2024-02-19 11:50:47 发布