本帖最后由 杨兴庭 于 2013-7-7 23:11 编辑
直接上代码,问题在代码里,先上类加载器- package study.day2;
- import java.io.*;
- import com.sun.beans.finder.ClassFinder;
- public class MyClassLoader extends ClassLoader{
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- String srcPath = args[0];
- String destDir = args[1];
- FileInputStream fis = new FileInputStream(srcPath);
- String destFileName = srcPath.substring(srcPath.lastIndexOf('\\'));
- String destPath = destDir+destFileName;
- FileOutputStream fos = new FileOutputStream(destPath);
- cypher(fis,fos);
- fis.close();
- fos.close();
- }
- //加密方法
- public static void cypher(InputStream fis, OutputStream fos) throws Exception {
- int b = -1;
- while((b=fis.read())!=-1){
- fos.write(b ^ 0xff);
- }
- }
- private String classDir;
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- String classFileName = classDir+"\\"+name.substring(name.lastIndexOf('.')+1)+".class";
- try {
- System.out.println("It's MyClassLoader.");
- FileInputStream fis = new FileInputStream(classFileName);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- cypher(fis,bos);
- byte[] bys = bos.toByteArray();
- return defineClass(null, bys, 0,bys.length);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- return super.findClass(name);
- }
- public MyClassLoader(String classDir){
- this.classDir = classDir;
- }
- }
复制代码 调用类加载器的代码- package study.day2;
- import java.util.Date;
- public class ClassLoderTest {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- /*
- System.out.println(ClassLoderTest.class.getClassLoader().getClass().getName());
- System.out.println(System.class.getClassLoader());
-
- ClassLoader loader = ClassLoader.class.getClassLoader();
- while(loader!=null){
- System.out.println(loader.getClass().getName());
- loader = loader.getParent();
- }
- System.out.println(loader);
- //System.out.println(new ClassLoaderAttachment().toString());
- */
- //问题在这里,看这里,看这里!!
- Class clazz = new MyClassLoader("itcastlib").loadClass("study.day2.ClassLoaderAttachment");//这里我明明是获取的ClassLoaderAttachment的字节码?
- Date dd = (Date) clazz.newInstance();//但是这里却要用ClassLoaderAttachment的父类来引用和强转,不明白其中的道理,求大家帮助
- System.out.println(dd);
- }
- }
复制代码 类加载需要加载的类的代码- package study.day2;
- import java.util.Date;
- public class ClassLoaderAttachment extends Date {
- @Override
- public String toString() {
- return "hello,itcast";
- }
- }
复制代码 疑问在调用类加载的代码里,麻烦大家帮我看看. |