public class FileSystemClassLoader extends ClassLoader {
????//com.bjsxt.test.User? --> d:/myjava/? com/bjsxt/test/User.class? ? ?
????private String rootDir;
????public FileSystemClassLoader(String rootDir){
????this.rootDir = rootDir;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
????Class<?> c = findLoadedClass(name);
????//應(yīng)該要先查詢有沒有加載過這個(gè)類。如果已經(jīng)加載混巧,則直接返回加載好的類勤揩。如果沒有,則加載新的類傍衡。
????if(c!=null){
????????return c;
????}else{
????????ClassLoader parent = this.getParent();
????try {
????????c = parent.loadClass(name); ? //委派給父類加載
????} catch (Exception e) {
????????// e.printStackTrace();
????}
????????if(c!=null){
????????????return c;
????????//找不到就自己加載
????????}else{
????????????byte[] classData = getClassData(name);
????????????if(classData==null){
????????????????throw new ClassNotFoundException();
????????????}else{
????????????????c = defineClass(name, classData, 0,classData.length);
????????????}
????????}
????}
return c;
}
????private byte[] getClassData(String classname){? //com.bjsxt.test.User? d:/myjava/? com/bjsxt/test/User.class
????????String path = rootDir +"/"+ classname.replace('.', '/')+".class";
????????// IOUtils,可以使用它將流中的數(shù)據(jù)轉(zhuǎn)成字節(jié)數(shù)組
????????InputStream is = null;
????????ByteArrayOutputStream baos = new ByteArrayOutputStream();
????????try{
????????????is? = new FileInputStream(path);
????????????byte[] buffer = new byte[1024];
????????????int temp=0;
????????????while((temp=is.read(buffer))!=-1){
????????????baos.write(buffer, 0, temp);
????????????}
????????return baos.toByteArray();
????????}catch(Exception e){
????????????e.printStackTrace();
????????????return null;
????????}finally{
????????????try {
????????????????if(is!=null){
????????????????????is.close();
????????????????}
????????????} catch (IOException e) {
????????????????e.printStackTrace();
????????????}
????????????try {
????????????????if(baos!=null){
????????????????????baos.close();
????????????????}
????????????} catch (IOException e) {
????????????????e.printStackTrace();
????????????}
????????}
????}
}