- package com.itheima.day02;
- import java.io.ByteArrayOutputStream;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- public class MyClassLoader extends ClassLoader
- {
- public static void main(String[] args) throws Exception
- {
- String srcPath=args[0];
- String descPath=args[1];
- FileInputStream fis=new FileInputStream(srcPath);
- FileOutputStream fos=new FileOutputStream(descPath);
- cypher(fis, fos);
- fis.close();
- fos.close();
- }
-
- private static void cypher(InputStream is,OutputStream os)throws Exception
- {
- int b=0;
- while((b=is.read())!=-1)
- {
- os.write(b^0xFF);
- }
- }
- private String classDir;
-
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException
- {
- String classFileName=classDir+"\\"+name+".class";
- try
- {
- FileInputStream fis=new FileInputStream(classFileName);
- ByteArrayOutputStream bos=new ByteArrayOutputStream();
- cypher(fis,bos);
- fis.close();
- byte[] bytes=bos.toByteArray();
- return defineClass(bytes, 0, bytes.length);
- }
- catch (FileNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- catch (Exception e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return super.findClass(name);
- }
-
- public MyClassLoader(){}
-
- public MyClassLoader(String classDir)
- {
- this.classDir=classDir;
- }
- }
复制代码- package com.itheima.day02;
- public class ClassLoaderTest
- {
- public static void main(String[] args)
- {
- System.out.println(ClassLoaderTest.class.getClassLoader().getClass()
- .getName());
- // System.out.println(System.class.getClassLoader());
-
- ClassLoader loader=ClassLoaderTest.class.getClassLoader();
- while(loader!=null)
- {
- System.out.println(loader.getClass().getName());
- loader=loader.getParent();
- }
- System.out.println(loader);
- }
- }
复制代码- package com.itheima.day02;
- import java.util.Date;
- public class ClassLoaderAttachment extends Date
- {
- public String toString()
- {
- return "hello";
- }
- }
复制代码
请亲们给我详细的解释一下,关于类加载器的相关问题,听这儿的时候有点晕。。
还有上面代码的具体解释,原理。
|