标签:catch 重写 service bytes style get 根据 生命周期 java虚拟机
static { i = 5; //System.out.println(i); } static int i;
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { // First, check if the class has already been loaded Class<?> c = findLoadedClass(name); if (c == null) { long t0 = System.nanoTime(); try { if (parent != null) { c = parent.loadClass(name, false); } else { c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent class loader } if (c == null) { // If still not found, then invoke findClass in order // to find the class. long t1 = System.nanoTime(); c = findClass(name); // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { resolveClass(c); } return c; } }
public class MyClassLoader extends ClassLoader { public MyClassLoader() { } public MyClassLoader(ClassLoader parent) { super(parent); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try{ /** * defineClass方法可以把二进制流字节组成的文件转换为一个java.lang.Class * @bytes 是class文件生成的byte[] * @ */ Class<?> c = this.defineClass(name, bytes, 0, bytes.length); return c; } catch (Exception e) { } return super.findClass(name); } }
public static void main(String[] args) throws Exception{ //使用forName来指定类加载器创建对象 MyClassLoader mcl = new MyClassLoader(); Class<?> clazz = Class.forName("People", true, mcl); Object people =clazz.newInstance(); System.out.println(people); System.out.println(people.getClass().getClassLoader()); //直接使用自定义类加载器来得到Class对象,loadClass会调用findClass方法返回Class对象 Class<?> clazz1 = mcl.loadClass("People"); // 加载一个版本的类 Object obj = clazz1.newInstance(); // 创建对象 System.out.println(obj); System.out.println(obj.getClass().getClassLoader()); }
注意 :这里clazz.newInstance();不能强转 People people = (People)clazz.newInstance(),这是因为clazz.newInstance()是由MyClassLoader()加载,(People)是由AppClassLoader加载,jvm认为他们不是同类型所以报ClassCastException异常
标签:catch 重写 service bytes style get 根据 生命周期 java虚拟机
原文地址:https://www.cnblogs.com/mibloom/p/9608895.html