自己写了一个类加载器,为什么张老师调用的时候用:new Loader("E:\\MyEclipse Professional 2014\\exam\\bin").loadClass("Loader_HelloWorld");
我像张老师那样调用就不行,下面是我的代码,我这样调用,算不算是我写的加载器是有效的?我打印出的结果是这样的:
com.classLoader.Loader@dd41677
sun.misc.Launcher$AppClassLoader@5552bb15
sun.misc.Launcher$ExtClassLoader@2a788b76
自定义类加载器开始啦!!!!!!
加载器
----------------------------------------ClassLoader_demo 主类---------------------------------------------------------
package com.classLoader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
public class ClassLoader_demo {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
// TODO Auto-generated method stub
Loader ld = new Loader("E:\\MyEclipse Professional 2014\\exam\\bin");
Class<?> ls = ld.findClass("com.classLoader.Loader_HelloWorld");
Date t = (Date)ls.newInstance();
System.out.println(t.toString());
}
}
class Loader extends ClassLoader{
private String dir;
Loader(String dir){
this.dir = dir;
}
public String path(String classname){
String classpath = dir + File.separatorChar + classname.replace('.',File.separatorChar)+".class";
return classpath;
}
public byte[] file(String classpath) throws IOException{
String classpath1 = path(classpath);
InputStream ius = new FileInputStream(classpath1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//byte[] bt = new byte[2014];
int k = -1;
while((k = ius.read())!=-1){
baos.write(k^0xff);
}
return baos.toByteArray();
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
byte[] bt = file(name);
if(bt == null)
throw new ClassNotFoundException();
else{
return defineClass(bt,0,bt.length);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
};
}
------------------------------Loader_HelloWorld 调用类----------------------------------
package com.classLoader;
import java.util.Date;
public class Loader_HelloWorld extends Date{
public String toString(){
Loader_HelloWorld();
String s = "加载器";
return s;
}
public void Loader_HelloWorld() {
ClassLoader loader = Loader_HelloWorld.class.getClassLoader();
while(loader != null){
System.out.println(loader.toString());
loader = loader.getParent();
}
System.out.println("自定义类加载器开始啦!!!!!!");
}
}
|
|