标签:color win nts 代码 类装载 not rac ssl 路径
(1)MyClassLoader
public class MyClassLoader extends ClassLoader { private String path; private String classLoaderName; public MyClassLoader(String path, String classLoaderName) { this.path = path; this.classLoaderName = classLoaderName; } //用于寻找类文件 @Override public Class findClass(String name) { byte[] b = loadClassData(name); return defineClass(name, b, 0, b.length); } //用于加载类文件 private byte[] loadClassData(String name) { name = path + name + ".class"; InputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(new File(name)); out = new ByteArrayOutputStream(); int i = 0; while ((i = in.read()) != -1) { out.write(i); } } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } return out.toByteArray(); } }
原理还是通过ClassLoader中的deFineClass方法来获取Class类型对象,自定义的是路径
(2)实现ClassLoaderChecker
public class ClassLoaderChecker { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException { MyClassLoader m = new MyClassLoader("/Users/baidu/Desktop/", "myClassLoader"); Class c = m.loadClass("Wali"); c.newInstance(); } }
(3)实现效果
4.类加载器的双亲委派机制
为什么要使用双亲委派机制来加载class文件-避免多份同样的字节码的加载
隐式加载:new
显示加载:loadClass,formName
(1)类装载过程
(2)代码实例区别
public class LoadDifference { public static void main(String[] args) throws Exception { //loadClass加载类,需要调用c.newInstance()才会加载类 ClassLoader cl = Robot.class.getClassLoader(); Class c = cl.loadClass("com.interview.javabasic.reflect.Robot"); c.newInstance(); //forName加载类,在加载类的时候会将Static静态代码块的代码实现出来 Class r = Class.forName("com.interview.javabasic.reflect.Robot"); } }
使用Class.forName(classname)才能在反射回去类的时候执行static块。(3)数据库链接为什么使用Class.forName(className)
标签:color win nts 代码 类装载 not rac ssl 路径
原文地址:https://www.cnblogs.com/xzmxddx/p/10366880.html