- package pack;
- import java.io.*;
- import java.lang.reflect.*;
- public class MyClassLoader extends ClassLoader
- {
- private String path = null;
- public MyClassLoader(String path) throws Exception//检查文件是否存在
- {
- File f = new File(path);
- if(!f.isDirectory())
- {
- throw new RuntimeException(path + " is not a directory");
- }
- this.path = path;
- }
-
- public Class findClass(String name)
- {
- try
- {
- File f = new File(path,name.substring(name.lastIndexOf('.')+1) + ".class");
- FileInputStream fis = new FileInputStream(f);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- cypher(fis,bos);
- byte [] buf = bos.toByteArray();
- fis.close();
- bos.close();
- return defineClass(name,buf,0,buf.length);
- }catch(Exception e)
- {
- try {
- throw new ClassNotFoundException(name + " is not found!");
- } catch (ClassNotFoundException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- return null;
- }
-
- public static void cypher(InputStream istream,OutputStream ostream) throws Exception
- {
-
- int b = 0;
- while((b = istream.read()) != -1)
- {
- ostream.write(((byte)b) ^ 0xff);
- }
- }
- public static void main(String [] args) throws Exception
- {
- if(!args[0].endsWith("class"))
- {
- ClassLoader loader = new MyClassLoader(args[1]);
- Class cls = loader.loadClass(args[0]);
-
-
- //让自定义类继承Date类
- System.out.println(cls.getClassLoader().getClass().getName());
- java.util.Date d = (java.util.Date)cls.newInstance();
- System.out.println(d.toString());
-
-
- Method m = cls.getMethod("test");
- m.invoke(cls.newInstance());
- return;
- }
- else
- {
- FileInputStream fis = new FileInputStream(args[0]);
- File f = new File(args[1], new File(args[0]).getName());//不用检查目录最后是否有目录分割符
- FileOutputStream fos = new FileOutputStream(f);
- cypher(fis,fos);
- fis.close();
- fos.close();
- }
- }
- }
复制代码 为什么运行结果报异常,找很久都找不出来啊?- Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
- at pack.MyClassLoader.main(MyClassLoader.java:56)
复制代码 |