龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

玩转Java的CLASSPATH(三)JWhich的工作过程[组图]

时间:2009-12-23 15:42来源:未知 作者:admin 点击:
分享到:
四、JWhich的工作过程 要精确地测定classpath中哪一个类先被装载,你必须深入到类装载器的思考方法。事实上,具体实现的时候并没有听起来这么复杂――你只需直接询问类装载器就可以
四、JWhich的工作过程
     要精确地测定classpath中哪一个类先被装载,你必须深入到类装载器的思考方法。事实上,具体实现的时候并没有听起来这么复杂――你只需直接询问类装载器就可以了!
  
   1: public class JWhich {
   2:
   3: /**
   <!-- frame contents -->
<!-- /frame contents --> 4: * 根据当前的classpath设置,
   5: * 显示出包含指定类的类文件所在
   6: * 位置的绝对路径
   7: *
   8: * @param className <类的名字>
   9: */
   10: public static void which(String className) {
   11:
   12: if (!className.startsWith("/")) {
   13: className = "/" + className;
   14: }
   15: className = className.replace('.', '/');
   16: className = className + ".class";
   17:
   18: Java.net.URL classUrl =
   19: new JWhich().getClass().getResource(className);
   20:
   21: if (classUrl != null) {
   22: System.out.println(" Class '" + className +
   23: "' found in '" + classUrl.getFile() + "'");
   24: } else {
   25: System.out.println(" Class '" + className +
   26: "' not found in '" +
   27: System.getProperty("java.class.path") + "'");
   28: }
   29: }
   30:
   31: public static void main(String args[]) {
   32: if (args.length > 0) {
   33: JWhich.which(args[0]);
   34: } else {
   35: System.err.println("Usage: java JWhich ");
   36: }
   37: }
   38: }
  
     首先,你必须稍微调整一下类的名字以便类装载器能够接受(12-16行)。在类的名字前面加上一个“/”表示要求类装载器对classpath中的类名字进行逐字精确匹配,而不是尝试隐含地加上调用类的包名字前缀。把所有“.”转换为“/”的目的是,按照类装载器的要求,把类名字格式化成一个合法的URL资源名。
  
     接下来,程序向类装载器查询资源,这个资源的名字必须和经过适当格式化的类名字匹配(18-19行)。每一个Class对象维护着一个对装载它的ClassLoader对象的引用,所以这里是向装载JWhich类的类装载器查询。Class.getResource()方法实际上委托装入该类的类装载器,返回一个用于读取类文件资源的URL;或者,当指定的类名字不能在当前的classpath中找到时,Class.getResource()方法返回null。
  
  
精彩图集

赞助商链接