您的位置:首页 > 其它

模拟jvm类双亲委托加载机制

2017-11-09 00:00 190 查看
jdk源代码,以及流程图如下





模拟代码

package test.com.shareinfo.app;

public abstract class AbstrFather {
public AbstrFather parent;

protected String loadClass(String str) throws Exception {
String var4 = null;
try {
if (this.parent != null) {
System.out.println(this.getClass() + " 拥有父加载器,移交给" + this.parent.getClass() + "加载");
var4 = this.parent.loadClass(str);
} else {
var4 = this.findBootstrapClassOrNull(str);
}
} catch (Exception var10) {
System.out.println(var10.getMessage());
;

}

if (var4 == null) {
var4 = this.findClass(str);
}
return var4;
}

protected abstract String findClass(String str) throws Exception;

public String findBootstrapClassOrNull(String str) throws Exception {
throw new Exception(this.getClass() + " find class error");
}

public AbstrFather getParent() {
return parent;
}

public void setParent(AbstrFather parent) {
this.parent = parent;
}

}


三个加载类的代码

public class BootClass extends AbstrFather {

@Override
protected String findClass(String str) throws Exception {
throw new Exception(this.getClass() + "  findClass error");
}

}

public class ExtClass extends AbstrFather {

@Override
protected String findClass(String str) throws Exception {
throw new Exception(this.getClass() + "  findClass error");
}

}

public class AppClass extends AbstrFather {

@Override
protected String findClass(String str) throws Exception {
System.out.println(this.getClass() + "  findClass success");
return "myload";
}

}

测试代码

public class LoadTest {

public static void main(String[] args) throws ClassNotFoundException {

AbstrFather my = new AppClass();
BootClass bc = new BootClass();
ExtClass ec = new ExtClass();
ec.setParent(bc);
my.setParent(ec);
try {
my.loadClass("1");
} catch (Exception e) {

e.printStackTrace();
}

}

}

结果打印

class test.com.shareinfo.app.AppClass 拥有父加载器,移交给class test.com.shareinfo.app.ExtClass加载
class test.com.shareinfo.app.ExtClass 拥有父加载器,移交给class test.com.shareinfo.app.BootClass加载
class test.com.shareinfo.app.BootClassbootStrp find class error
class test.com.shareinfo.app.BootClass  findClass error
class test.com.shareinfo.app.ExtClass  findClass error
class test.com.shareinfo.app.AppClass  findClass success
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: