`
ravenex
  • 浏览: 10932 次
  • 性别: Icon_minigender_1
  • 来自: 体育仓库
社区版块
存档分类
最新评论

谁是initiating loader

阅读更多
《深入Java虚拟机》第二版(很老的那本,Bill Venners写的,有中文翻译那本)第八章讲解类加载器用了个Cindy、Mom、Grandma的例子。但那个例子是错的。发了邮件到jdk6-dev邮件列表,等待答复。顺便发这边大家讨论。

那个例子说,Cindy的parent是Mom,Mom的parent是Grandma,Grandma的parent是null也就是bootstrap class loader。
Cindy尝试加载java.io.FileReader会委派给Mom,Mom委派给Grandma,Grandma委派给bootstrap,bootstrap成功加载并一层层把Class返回出来。
这个过程完成后,书上说Cindy、Mom、Grandma都应该是initiating loader。但事实却不是如此。

代码例子:
import java.io.*;
import java.net.*;

public class TestInitiatingLoader {
  public static void main(String[] args) throws Exception {
    Grandma grandma = new Grandma();
    Mom mom = new Mom(grandma);
    Cindy cindy = new Cindy(mom);
    cindy.loadClass("Dummy").newInstance(); // force class init
    
    final String reader = "java.io.FileReader";
    printStats(grandma, reader); // false
    printStats(mom, reader);     // false
    printStats(cindy, reader);   // true
  }
  
  private static void printStats(LoadedClassQueryable loader, String name) {
    System.out.printf("Is %s an initiating loader of %s: %b\n",
      loader.getClass().getName(),
      name,
      loader.foundLoadedClass(name));
  }
}

interface LoadedClassQueryable {
  boolean foundLoadedClass(String name);
}

class Cindy
    extends URLClassLoader
    implements LoadedClassQueryable {
  public Cindy(ClassLoader parent) {
    super(makeArgs(), parent);
  }
  
  private static URL[] makeArgs() {
    try {
      return new URL[] { new File(".").toURI().toURL() };
    } catch (Exception e) {
      e.printStackTrace();
      return new URL[] { };
    }
  }
  
  @Override
  public Class<?> loadClass(String name) throws ClassNotFoundException {
    if ("Dummy".equals(name)) {
      // force Cindy to load this Dummy class
      return findClass("Dummy");
    }
    return super.loadClass(name);
  }
  
  @Override
  public boolean foundLoadedClass(String name) {
    return findLoadedClass(name) != null;
  }
}

class Mom
    extends ClassLoader
    implements LoadedClassQueryable {
  public Mom(ClassLoader parent) {
    super(parent);
  }
  
  @Override
  public boolean foundLoadedClass(String name) {
    return findLoadedClass(name) != null;
  }
}

class Grandma
    extends ClassLoader
    implements LoadedClassQueryable {
  public Grandma() {
    super(null); // use bootstrap class loader as parent
  }
  
  @Override
  public boolean foundLoadedClass(String name) {
    return findLoadedClass(name) != null;
  }
}

Dummy.java
import java.io.*;

public class Dummy {
  static {
    // Dummy should be loaded by Cindy.
    // So Cindy will be recorded as an initiating loader for java.io.FileReader
    try {
      new FileReader("Dummy.class").close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


运行结果:
Is Grandma an initiating loader of java.io.FileReader: false
Is Mom an initiating loader of java.io.FileReader: false
Is Cindy an initiating loader of java.io.FileReader: true


ClassLoader.findLoadedClass()可用于确认一个类与initiating loader关系。
引用
findLoadedClass

protected final Class<?> findLoadedClass(String name)
Returns the class with the given binary name if this loader has been recorded by the Java virtual machine as an initiating loader of a class with that binary name. Otherwise null is returned.

Parameters:
name - The binary name of the class
Returns:
The Class object, or null if the class has not been loaded
Since:
1.1


读书要谨慎,切记不要人云亦云。
分享到:
评论
2 楼 ravenex 2012-11-05  
chong_zh 写道
例子中的Cindy,Mom,Grandma并没有载入委派关系,委派是指调用被委派对象的loadClass方法,以Cindy的loadClass方法为例:

  public Class<?> loadClass(String name) throws ClassNotFoundException {  
    if ("Dummy".equals(name)) {  
      // force Cindy to load this Dummy class  
      return findClass("Dummy");  
    }  
    return getParent().loadClass(name);  
  } 


所以您没看懂super.loadClass(name)的意义。这里调用的是ClassLoader.loadClass(String name)(因为URLClassLoader没有override掉ClassLoader的loadClass方法),里面一进去如果检查到指定名字的类没加载过就会用parent.loadClass(name),或如果parent是null则用bootstrap class loader来加载。
1 楼 chong_zh 2012-08-26  
例子中的Cindy,Mom,Grandma并没有载入委派关系,委派是指调用被委派对象的loadClass方法,以Cindy的loadClass方法为例:

  public Class<?> loadClass(String name) throws ClassNotFoundException {  
    if ("Dummy".equals(name)) {  
      // force Cindy to load this Dummy class  
      return findClass("Dummy");  
    }  
    return getParent().loadClass(name);  
  } 

相关推荐

    School psychologists as researchers: An approach for initiating training and practice

    School psychologists as researchers: An approach for initiating training and practice PsyrholoRj in thr Schoo/s Volume 21 . A d , /984 SCHOOL PSYCHOLOGISTS AS RESEARCHERS: AN APPROACH FOR ...

    initiating_git

    第一个仓库在这里,我保留了我在python中制作的第一个程序,它们非常简单并且易于实践

    workflow student guide-工作流手册

    Workflow Definitions Loader 2-11 Notification System 2-12 Notification Web Page 2-13 E-Mail Notification 2-14 Notification Viewer Form 2-15 Workflow Monitor 2-16 Summary 2-18 Lesson 3: Overview of the...

    DragController.rar_class A

    Class for initiating a drag within a view or across multiple views.

    NewHO.rar_DSP编程_PDF_

    New Handoff initiating Algorithm

    vanillamod-transpiler:为Vanillamod.com网站制作的VanillaMod的编译器,编辑器和文档

    vMod vMod是网站背后的开源库。 vMod将JavaScript转换为Minecraft命令(如/gamemode creative )。 结果是一种真正的编程语言的实用性,以及香草Minecraft的功能和兼容性... log ( "Initiating countdown sequence!" )

    PMP Project Management Professional Practice Test

    Five unique 160- question chapter tests, as well as one practice exam cover Initiating; Planning; Executing; Monitoring and Controlling; and Closing to help you pinpoint weak areas while there is ...

    libzrtp源码

    ZRTP works by assuming control of the VoIP traffic and initiating an encrypted connection between two ZRTP endpoints after a safe mode is achieved. To integrate the library, please review our ...

    tsb.rar_On The Run

    TSB flushes need only occur on the processor initiating the address space modification, not on each cpu the address space has run on. Only the TLB flush needs that treatment.

    PMP八大会议

    包括PMP常用的八大会议资料,如 ...1、英文名称:initiating meeting; 2、召开时间:是启动阶段结束时召开的会议; 3、主要任务:发布项目章程,并任命项目经理,赋予项目经理动用组织资源的权力; 4、注意事项:

    pdsh-2.9.rar

    Pdsh uses a "sliding window" parallel algorithm to conserve socket resources on the initiating node and to allow progress to continue while timeouts occur on some connections. Pdsh is similar to DSH...

    Coding Faster: Getting More Productive with Microsoft Visual Studio

    Save time initiating a new project by creating custom templates Uncover secrets for working with the toolbox, commands, and window layouts Work with files in more practical ways, such as using the ...

    staxmem(手动安装IIS时,总是提示无法复制staxmem.dll及解决方法)

    Initiating INTEGRITY mode... Database: L:\WINDOWS\security\database\secedit.sdb Temp. Database: TEMPINTEG2680.EDB Checking database integrity. Scanning Status (% complete) 0 10 20 30 40 50 60 70 80...

    Code of practice for information security management AS/NZS ISO/IEC 17799:2001

    security management for use by those who are responsible for initiating, implementing or maintaining security in their organization. It is intended to provide a common basis for developing ...

    TICQconnection & ICQ_API(full_source)

    The API enables the query of data from the ICQ Client,initiating operations in the client and getting notifications from the client asynchronously.ICQ API FILESICQMsgAPI.lib - The ICQAPI library file...

    Wrox.Press.-.Professional..Programming.pdf

    Initiating a TCP connection 16-2. Exchanging messages with a SMTP server 16-3. whois_request() function 16-4. Simple whois frontend (HTML code) 16-5. Simple whois frontend (PHP code) 16-6. Source ...

    Advanced Global Navigation Satellite System Reciever Design.Y2007

    Abstract The research described by this thesis was undertaken at a very...schemes have been launched, initiating the modernisation of the American GPS and the introduction of the European Galileo system.

    Sybex.Project.Plus.Study.Guide.eBook-LiB.chm

    The four domains measured in CompTIA's 2003 version of the Project+ exam map to the five process groups that are the foundation of the Guide to the PMBOK : Initiating, Planning, Executing, ...

    Assignment

    Web-全栈Nest + Angular测试分配问题The app should consist of **two** screens:A **Home** screen containing two elements- Text field for entering an 'Id' Integer Value- 'Send' Button for initiating the ...

    LAN Intercom

    The initiating computer can select the computer to which it wishes to make a connection in a list displaying all the currently connected machines on which Lanic is running. Though Lanic makes use of ...

Global site tag (gtag.js) - Google Analytics