Java基础加强总结(4)(类加载器)

来源:互联网 发布:win10装mac系统 编辑:程序博客网 时间:2024/06/11 06:01

 

一、类加载器

加载类的工具

Java虚拟机提供了三个类加载器:

BootStrap:(C++实现的嵌在JVM内核里)-----jre/lib/rt.jar

ExtClassLoader:(Java类)-----jre/lib/ext/*.jar

AppClassLoader:(Java类)-----classPath指定的所有jar或目录

类加载器的委托机制

当Java虚拟机要加载一个类时,到底派出哪个类加载器去加载呢?

首先当前线程的类加载器去加载线程中的第一个类。

如果类A中引用了类B,Java虚拟机将使用加载类A的类加载器来加载类B。

还可以直接调用ClassLoader.loadClass()方法来指定某个类加载器去加载某个类。

 

每个类加载器加载类时,又先委托给其上级类加载器。

当所有祖宗类加载器没有加载到类,回到发起者类加载器,还加载不了,则抛ClassNotFoundException,不是在去找发起者类加载器的儿子。

模板方法设计模式

loadClass(加载类)---->findClass(找到类)---->definClass(得到class文件转换成字节码)

 用自定义类加载器加载加密过的字节码文件

package day3;import java.util.Date;public class ClassLoaderAttachment extends Date {public String toSting(){return "hello,itcast";}}
package day3;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class MyClassLoader extends ClassLoader{static String destDir = null;MyClassLoader(String destDir){this.destDir = destDir;}public static void main(String[] args) throws Exception{String srcPath = args[0];destDir = args[1];inout(srcPath, destDir);ClassLoaderAttachment a = new ClassLoaderAttachment();System.out.println(a.toSting());}private static void inout(String srcPath, String destDir)throws FileNotFoundException, Exception, IOException {FileInputStream fis = new FileInputStream(srcPath);String destFileName = srcPath.substring(srcPath.lastIndexOf('\\')+1);String destPath = destDir + "\\" + destFileName;FileOutputStream fos = new FileOutputStream(destPath);cypher(fis,fos);fis.close();fos.close();}private static void cypher(InputStream ips,OutputStream ops) throws Exception{int b = -1;while((b=ips.read())!=-1){ops.write(b ^ 0xff);}}@Overrideprotected Class<?> findClass(String name) throws ClassNotFoundException{String classFileName = destDir +"\\" +name + ".class";try {FileInputStream fis = new FileInputStream(classFileName);ByteArrayOutputStream bos = new ByteArrayOutputStream();cypher(fis,bos);fis.close();} catch (Exception e)  {e.printStackTrace();}return super.findClass(name);}}
package day3;import java.util.Date;public class TestDemo {public static void main(String[] args) throws Exception{Class clazz = new MyClassLoader("itcastlib").loadClass("day3.ClassLoaderAttachment");Date d1 = (Date)clazz.newInstance();System.out.println(d1);}}

 

原创粉丝点击