WEB开发网
开发学院软件开发Java Java 编程的动态性,第 5 部分: 动态转换类 阅读

Java 编程的动态性,第 5 部分: 动态转换类

 2010-03-18 00:00:00 来源:WEB开发网   
核心提示: 清单 2. 一个详细的 classloaderpublicclassVerboseLoaderextendsURLClassLoader{protectedVerboseLoader(URL[]urls,ClassLoaderparent){super(urls,parent);}publicC

清单 2. 一个详细的 classloader

public class VerboseLoader extends URLClassLoader 
{ 
  protected VerboseLoader(URL[] urls, ClassLoader parent) { 
    super(urls, parent); 
  } 
   
  public Class loadClass(String name) 
    throws ClassNotFoundException { 
    System.out.println("loadClass: " + name); 
    return super.loadClass(name); 
  } 
  protected Class findClass(String name) 
    throws ClassNotFoundException { 
    Class clas = super.findClass(name); 
    System.out.println("findclass: loaded " + name + 
      " from this loader"); 
    return clas; 
  } 
  public static void main(String[] args) { 
    if (args.length >= 1) { 
      try { 
         
        // get paths to be used for loading 
        ClassLoader base = 
          ClassLoader.getSystemClassLoader(); 
        URL[] urls; 
        if (base instanceof URLClassLoader) { 
          urls = ((URLClassLoader)base).getURLs(); 
        } else { 
          urls = new URL[] 
            { new File(".").toURI().toURL() }; 
        } 
         
        // list the paths actually being used 
        System.out.println("Loading from paths:"); 
        for (int i = 0; i < urls.length; i++) { 
          System.out.println(" " + urls[i]); 
        } 
         
        // load target class using custom class loader 
        VerboseLoader loader = 
          new VerboseLoader(urls, base.getParent()); 
        Class clas = loader.loadClass(args[0]); 
           
        // invoke "main" method of target class 
        Class[] ptypes = 
          new Class[] { args.getClass() }; 
        Method main = 
          clas.getDeclaredMethod("main", ptypes); 
        String[] pargs = new String[args.length-1]; 
        System.arraycopy(args, 1, pargs, 0, pargs.length); 
        Thread.currentThread(). 
          setContextClassLoader(loader); 
        main.invoke(null, new Object[] { pargs }); 
         
      } catch ... 
      } 
       
    } else { 
      System.out.println 
        ("Usage: VerboseLoader main-class args..."); 
    } 
  } 
} 

上一页  1 2 3 4 5 6 7 8 9  下一页

Tags:Java 编程 动态性

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接