额,我把自己的视频学习笔记贴出来,别介意哦,只求一技术分,你懂的:'(- 注:类加载中如果类A引用到了类B(如 A继承B,A中New B()),是用加载类A的类加载器去加载类B!
- 获取一个类的加载器的名称的方法
- 如获取:ClassLoaderTest的加载器的名称的方法
- ClassLoaderTest.class.getClassLoader().getClass().getName()
- 自定义类加载器(继承ClassLoader,重写findClass()方法,loadClass保存了类加载器的委托机制,所有最好不要重写loadclass方法,在类加载器中如果loadclass找不到类会调用findclass方法继续查找)
- public class MyClassLoader extends ClassLoader{
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- String srcPath = args[0];
- String destDir = args[1];
- 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);
- }
- }
- private String classDir;
- //必须重写findClass方法
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- // TODO Auto-generated method stub
- String classFileName = classDir + "\\" + name.substring(name.lastIndexOf('.')+1) + ".class";
- try {
- FileInputStream fis = new FileInputStream(classFileName);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- cypher(fis,bos);
- fis.close();
- System.out.println("aaa");
- byte[] bytes = bos.toByteArray();
- return defineClass(bytes, 0, bytes.length);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
-
- public MyClassLoader(){
-
- }
-
- public MyClassLoader(String classDir){
- this.classDir = classDir;
- }
- }
- 调用方法:
- Class clazz = new MyClassLoader("itcastlib").loadClass("cn.itcast.day2.ClassLoaderAttachment");
- Date d1 = (Date)clazz.newInstance();
复制代码 |