/Users/lyon/j4p/src/javassist/LoaderClassPath.java

1    /* 
2     * Javassist, a Java-bytecode translator toolkit. 
3     * Copyright (C) 1999-2003 Shigeru Chiba. All Rights Reserved. 
4     * 
5     * The contents of this file are subject to the Mozilla Public License Version 
6     * 1.1 (the "License"); you may not use this file except in compliance with 
7     * the License.  Alternatively, the contents of this file may be used under 
8     * the terms of the GNU Lesser General Public License Version 2.1 or later. 
9     * 
10    * Software distributed under the License is distributed on an "AS IS" basis, 
11    * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
12    * for the specific language governing rights and limitations under the 
13    * License. 
14    */ 
15    
16   package javassist; 
17    
18   import java.io.InputStream; 
19   import java.lang.ref.WeakReference; 
20    
21   /** 
22    * A class search-path representing a class loader. 
23    * 
24    * <p>It is used for obtaining a class file from the given 
25    * class loader by <code>getResourceAsStream()</code>. 
26    * The <code>LoaderClassPath</code> refers to the class loader through 
27    * <code>WeakReference</code>.  If the class loader is garbage collected, 
28    * the other search pathes are examined. 
29    * 
30    * @author <a href="mailto:bill@jboss.org">Bill Burke</a> 
31    * @author Shigeru Chiba 
32    * 
33    * @see javassist.ClassPath 
34    * @see ClassPool#insertClassPath(ClassPath) 
35    * @see ClassPool#appendClassPath(ClassPath) 
36    */ 
37   public class LoaderClassPath implements ClassPath { 
38       private WeakReference clref; 
39    
40       /** 
41        * Creates a search path representing a class loader. 
42        */ 
43       public LoaderClassPath(ClassLoader cl) { 
44           clref = new WeakReference(cl); 
45       } 
46    
47       public String toString() { 
48           Object cl = null; 
49           if (clref != null) 
50               cl = clref.get(); 
51    
52           return cl == null ? "<null>" : cl.toString(); 
53       } 
54    
55       /** 
56        * Obtains a class file from the class loader. 
57        */ 
58       public InputStream openClassfile(String classname) { 
59           String cname = classname.replace('.', '/') + ".class"; 
60           ClassLoader cl = (ClassLoader) clref.get(); 
61           if (cl == null) 
62               return null;        // not found 
63           else 
64               return cl.getResourceAsStream(cname); 
65       } 
66    
67       /** 
68        * Closes this class path. 
69        */ 
70       public void close() { 
71           clref = null; 
72       } 
73   } 
74