测试代码:

 class Hello
{
  public String str = "Hello World";
  public void fun()
  {
    System.out.println(str);
7   }
} public class Test{
  public static void main(String[] args)
  {
    Hello hello = new Hello();
    hello.fun();     System.out.println("----------------------");     //Hello类的类加载器
    ClassLoader classLoaderOfHello = Hello.class.getClassLoader();     System.out.println("Hello is Loaded by : "+classLoaderOfHello); 24     System.out.println("----------------------");     //Hello类的类加载器的Class对象
    Class AppClazz = classLoaderOfHello.getClass();     //分析Hello类的类加载器的Class对象的类继承关系
    while(AppClazz != null)
31     {
    System.out.println(AppClazz); 34     AppClazz = AppClazz.getSuperclass();
35     }     System.out.println("----------------------");     //取得扩展器加载器的类对象Class
    Class ExtClazz = classLoaderOfHello.getParent().getClass();     while(ExtClazz != null)
    {
    System.out.println(ExtClazz);     ExtClazz = ExtClazz.getSuperclass();
    }
  }
}

结论:

1.  用户自定义的类是由 应用(系统)类加载器AppClassLoader加载

2.  在”父亲委托机制”中,扩展类加载器ExtClassLoader是AppClassLoader的父亲,并不是继承关系,而是ExtClassLoader加载了AppClassLoader

3.  AppClassLoader 和 ExtClassLoader 都扩展于 URLClassLoader加载器.

4.  也同时说明AppClassLoader而非继承ExtClassLoader.

继承关系:

java.lang.Object

--- java.lang.ClassLoader
              --- java.security.SecureClassLoader
                      ---  java.net.URLClassLoader
                            --- sun.misc.Launcher$ExtClassLoader

java.lang.Object

--- java.lang.ClassLoader
              --- java.security.SecureClassLoader
                      ---  java.net.URLClassLoader
                            --- sun.misc.Launcher$AppClassLoader

其实很简单嘛,直接看AppClassLoader的源代码就可以了嘛,哈哈,终于找到了好东东,上

JDK7: http://download.java.net/openjdk/jdk7/

JDK6: http://download.java.net/openjdk/jdk6/

下载其源代码就可以了

现在直接来看其源代码:

/**
* The class loader used for loading from java.class.path.
* runs in a restricted security context.
*/
static class AppClassLoader extends URLClassLoader {

static {
ClassLoader.registerAsParallelCapable();
}

public static ClassLoader getAppClassLoader(final ClassLoader extcl)
throws IOException
{
final String s = System.getProperty("java.class.path");
final File[] path = (s == null) ? new File[0] : getClassPath(s);

return AccessController.doPrivileged(
new PrivilegedAction<AppClassLoader>() {
public AppClassLoader run() {
URL[] urls =
(s == null) ? new URL[0] : pathToURLs(path);
return new AppClassLoader(urls, extcl);
}
});
}

/*
* Creates a new AppClassLoader
*/
AppClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent, factory);
}

/**
* Override loadClass so we can checkPackageAccess.
*/
public Class loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
int i = name.lastIndexOf('.');
if (i != -1) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPackageAccess(name.substring(0, i));
}
}
return (super.loadClass(name, resolve));
}

/**
* allow any classes loaded from classpath to exit the VM.
*/
protected PermissionCollection getPermissions(CodeSource codesource)
{
PermissionCollection perms = super.getPermissions(codesource);
perms.add(new RuntimePermission("exitVM"));
return perms;
}

/**
* This class loader supports dynamic additions to the class path
* at runtime.
*
* @see java.lang.instrument.Instrumentation#appendToSystemClassPathSearch
*/
private void appendToClassPathForInstrumentation(String path) {
assert(Thread.holdsLock(this));

// addURL is a no-op if path already contains the URL
super.addURL( getFileURL(new File(path)) );
}

/**
* create a context that can read any directories (recursively)
* mentioned in the class path. In the case of a jar, it has to
* be the directory containing the jar, not just the jar, as jar
* files might refer to other jar files.
*/

private static AccessControlContext getContext(File[] cp)
throws java.net.MalformedURLException
{
PathPermissions perms =
new PathPermissions(cp);

ProtectionDomain domain =
new ProtectionDomain(new CodeSource(perms.getCodeBase(),
(java.security.cert.Certificate[]) null),
perms);

AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { domain });

return acc;
}
}

哈,看了AppClassLoader的源代码后,大家明白了吧,AppClassLoader 继承了URLClassLoader,而且构造函数是直接调用URLClassLoader的构造

函数,loadClass(String name, boolean resolve)方法只是简单做了包的安全检查,然后就调用ClassLoader的 loadClass(String name, boolean resolve)方法了,其它的话,也是差不多..所以其功能和URLClassLoader差不多...

在ExtClassLoader也差不多,大家看看源代码就明了的:

/*
* Creates a new ExtClassLoader for the specified directories.
*/
public ExtClassLoader(File[] dirs) throws IOException {
super(getExtURLs(dirs), null, factory);
}

private static File[] getExtDirs() {
String s = System.getProperty("java.ext.dirs");
File[] dirs;
if (s != null) {
StringTokenizer st =
new StringTokenizer(s, File.pathSeparator);
int count = st.countTokens();
dirs = new File[count];
for (int i = 0; i < count; i++) {
dirs[i] = new File(st.nextToken());
}
} else {
dirs = new File[0];
}
return dirs;
}

private static URL[] getExtURLs(File[] dirs) throws IOException {
Vector<URL> urls = new Vector<URL>();
for (int i = 0; i < dirs.length; i++) {
String[] files = dirs[i].list();
if (files != null) {
for (int j = 0; j < files.length; j++) {
if (!files[j].equals("meta-index")) {
File f = new File(dirs[i], files[j]);
urls.add(getFileURL(f));
}
}
}
}
URL[] ua = new URL[urls.size()];
urls.copyInto(ua);
return ua;
}

/*
* Searches the installed extension directories for the specified
* library name. For each extension directory, we first look for
* the native library in the subdirectory whose name is the value
* of the system property <code>os.arch</code>. Failing that, we
* look in the extension directory itself.
*/
public String findLibrary(String name) {
name = System.mapLibraryName(name);
URL[] urls = super.getURLs();
File prevDir = null;
for (int i = 0; i < urls.length; i++) {
// Get the ext directory from the URL
File dir = new File(urls[i].getPath()).getParentFile();
if (dir != null && !dir.equals(prevDir)) {
// Look in architecture-specific subdirectory first
// Read from the saved system properties to avoid deadlock
String arch = VM.getSavedProperty("os.arch");
if (arch != null) {
File file = new File(new File(dir, arch), name);
if (file.exists()) {
return file.getAbsolutePath();
}
}
// Then check the extension directory
File file = new File(dir, name);
if (file.exists()) {
return file.getAbsolutePath();
}
}
prevDir = dir;
}
return null;
}

private static AccessControlContext getContext(File[] dirs)
throws IOException
{
PathPermissions perms =
new PathPermissions(dirs);

ProtectionDomain domain = new ProtectionDomain(
new CodeSource(perms.getCodeBase(),
(java.security.cert.Certificate[]) null),
perms);

AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { domain });

return acc;
}
}

---------------------
作者:irelandken
来源:CSDN
原文:https://blog.csdn.net/irelandken/article/details/7046689
版权声明:本文为博主原创文章,转载请附上博文链接!

分析AppClassLoader,ExtClassLoader 和URLClassLoader 的关系的更多相关文章

  1. 源码分析:动态分析 Linux 内核函数调用关系

    源码分析:动态分析 Linux 内核函数调用关系 时间 2015-04-22 23:56:07  泰晓科技 原文  http://www.tinylab.org/source-code-analysi ...

  2. <十>面向对象分析之UML核心元素之关系

    关系        --->在UML中关系是非常重要的语义,它抽象出对象之间的联系,让对象构成特定的结构.        一,关联关系(association)

  3. 数据挖掘(data mining),机器学习(machine learning),和人工智能(AI)的区别是什么? 数据科学(data science)和商业分析(business analytics)之间有什么关系?

    本来我以为不需要解释这个问题的,到底数据挖掘(data mining),机器学习(machine learning),和人工智能(AI)有什么区别,但是前几天因为有个学弟问我,我想了想发现我竟然也回答 ...

  4. 使用UML工具分析类图与类的关系-bouml(java和C++)

    在分析类之间的关系时可以借助工具来实现. bouml是一个UML分析工具,最新的版本是收费的,但是之前的版本是免费的. 这里使用的是4.23版. Bouml安装: 安装软件就按照流程走就行了.但是第一 ...

  5. 通过分析iframe和无阻塞脚本关系能让我们更懂iframe

    在我上篇文章里,我提到一种使用iframe完成无阻塞脚本加载的方式,因为我对iframe的偏见很大,所以上篇文章里我没有展开讨论这个问题. 文章发表后有位网友问了我这样一个问题,下面是他问题的原文,如 ...

  6. spring源码分析系列2:Bean与BeanDefinition关系

    接口表示一种能力,实现了一个接口,即拥有一种能力. BeanDefinition与Bean的关系, 就好比类与对象的关系. 类在spring的数据结构就是BeanDefinition.根据BeanDe ...

  7. MyBatis源码分析(1)——整体依赖关系图

    后续补充更新

  8. 源码分析:静态分析 C 程序函数调用关系图

    http://www.tinylab.org/callgraph-draw-the-calltree-of-c-functions/

  9. 0032 Java学习笔记-类加载机制-初步

    JVM虚拟机 Java虚拟机有自己完善的硬件架构(处理器.堆栈.寄存器等)和指令系统 Java虚拟机是一种能运行Java bytecode的虚拟机 JVM并非专属于Java语言,只要生成的编译文件能匹 ...

随机推荐

  1. C++——动态内存分配1

    9.动态内存分配  new 类型名T(初值列表) 其功能是在程序执行期间申请用于存放T类型对象的内存空间,并依初值列表赋以初值,结果值:成功则T类型的指针,指向新分配的内存:失败则为0(null).若 ...

  2. 文本中自动出现的 &#8203

    文本中自动出现的 &#8203   所借鉴原页面地址:https://blog.csdn.net/judyc/article/details/53097142 因判断容器内字符长度来做其它处理 ...

  3. spring微服务实战 - 1 一个完整的HTTP JSON REST服务

    import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.Spr ...

  4. OpenTLD相关资料

    这是一位来自奥地利的博士生的博客 他的介绍如下: I am a PhD student at the Safety and Security Department of the Austrian In ...

  5. 插件与App的跳转,及路由的关系

    在SDK中 无法直接跳App 的界面,这个时候需要使用 路由,或者通过 NSClassFromString 的 presentViewController 来跳转. 直接贴代码: UIViewCont ...

  6. K3修改字段名

    在K3的BOS中,自定义字段之后我们往往会修改字段名,便于记忆和理解,但是修改字段名之后,只是数据库中的字段名被修改了,BOS中的字段标识并没有被修改,可以通过以下语句将标识和字段名改成一致. sel ...

  7. [CF467C] George and Job - DP,前缀和

    简单dp + 前缀和 你谷这乱标难度的风气真是-- #include <bits/stdc++.h> using namespace std; #define int long long ...

  8. PP: Pattern Trails: visual analysis of pattern transitions in subspaces

    Problem: 1. We can't find patterns in full attribute space, and patterns may only be found in smalle ...

  9. pytorch save model + Gmatch4py + jupyter debugger + community structure

    1. pytorch, 使用训练好的模型测试自己图片 2. [ pytorch ] ——基本使用:(2) 训练好的模型参数的保存以及调用 3. Gmatch4py 4. Network Analysi ...

  10. C#设置一个控件可以鼠标拖动

    C#设置一个控件可以鼠标拖动: 新建一个C#项目, 创建一个label控件, 设置label的鼠标按下和抬起事件分别为:label1_MouseDown和label1_MouseUp. 对代码进行如下 ...