黑马程序员技术交流社区
标题:
类加载器问题?
[打印本页]
作者:
吴小铁你好
时间:
2012-6-8 22:44
标题:
类加载器问题?
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)
复制代码
作者:
伊文龙
时间:
2012-6-8 23:04
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at pack.MyClassLoader.main(MyClassLoader.java:56)
楼主不会看不懂这个异常吧,代码56行数组下表越界异常
你main方法的args[]参数根本没有传任何东西,
if(!args[0].endsWith("class"))
你这样搞,当然会抛异常了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2