您的位置:首页 > 其它

类加载器

2015-09-11 13:20 316 查看
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
}
else if (this.classLoader != null) {
is = this.classLoader.getResourceAsStream(this.path);
}
else {
is = ClassLoader.getSystemResourceAsStream(this.path);
}

1.this.clazz.getResourceAsStream(this.path)或this.classLoader.getResourceAsStream(this.path)原理:
首先获取加载该类的类加载器,然后调用getResourceAsStream 最终通过调用
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}

public URL getResource(String name) {
URL url;
if (parent != null) {
url = parent.getResource(name);
} else {
url = getBootstrapResource(name);
}
if (url == null) {
url = findResource(name);
}
return url;
}
首先调用父类的加载器,通过递归调用,父类加载器不存在就调用jvm的根类加载器

2.ClassLoader.getSystemResourceAsStream(this.path) 原理:

public static InputStream getSystemResourceAsStream(String name) {
URL url = getSystemResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}

public static URL getSystemResource(String name) {
ClassLoader system = getSystemClassLoader();
if (system == null) {
return getBootstrapResource(name);
}
return system.getResource(name);
}

直接调用系统类加载器,不存在的话就调用jvm的根类加载器
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: