View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.bcel.util;
20  
21  import java.io.ByteArrayInputStream;
22  import java.io.IOException;
23  import java.util.Hashtable;
24  
25  import org.apache.bcel.Const;
26  import org.apache.bcel.classfile.ClassParser;
27  import org.apache.bcel.classfile.ConstantClass;
28  import org.apache.bcel.classfile.ConstantPool;
29  import org.apache.bcel.classfile.ConstantUtf8;
30  import org.apache.bcel.classfile.JavaClass;
31  import org.apache.bcel.classfile.Utility;
32  
33  /**
34   * <p>
35   * Drop in replacement for the standard class loader of the JVM. You can use it in conjunction with the JavaWrapper to
36   * dynamically modify/create classes as they're requested.
37   * </p>
38   *
39   * <p>
40   * This class loader recognizes special requests in a distinct format, i.e., when the name of the requested class
41   * contains with "$$BCEL$$" it calls the createClass() method with that name (everything bevor the $$BCEL$$ is
42   * considered to be the package name. You can subclass the class loader and override that method. "Normal" classes class
43   * can be modified by overriding the modifyClass() method which is called just before defineClass().
44   * </p>
45   *
46   * <p>
47   * There may be a number of packages where you have to use the default class loader (which may also be faster). You can
48   * define the set of packages where to use the system class loader in the constructor. The default value contains
49   * "java.", "sun.", "javax."
50   * </p>
51   *
52   * @see JavaWrapper
53   * @see ClassPath
54   * @deprecated 6.0 Do not use - does not work
55   */
56  @Deprecated
57  public class ClassLoader extends java.lang.ClassLoader {
58  
59      private static final String BCEL_TOKEN = "$$BCEL$$";
60  
61      public static final String[] DEFAULT_IGNORED_PACKAGES = {"java.", "javax.", "sun."};
62  
63      private final Hashtable<String, Class<?>> classes = new Hashtable<>();
64      // Hashtable is synchronized thus thread-safe
65      private final String[] ignoredPackages;
66      private Repository repository = SyntheticRepository.getInstance();
67  
68      /**
69       * Ignored packages are by default ( "java.", "sun.", "javax."), i.e. loaded by system class loader
70       */
71      public ClassLoader() {
72          this(DEFAULT_IGNORED_PACKAGES);
73      }
74  
75      /**
76       * @param deferTo delegate class loader to use for ignored packages
77       */
78      public ClassLoader(final java.lang.ClassLoader deferTo) {
79          super(deferTo);
80          this.ignoredPackages = DEFAULT_IGNORED_PACKAGES;
81          this.repository = new ClassLoaderRepository(deferTo);
82      }
83  
84      /**
85       * @param ignoredPackages classes contained in these packages will be loaded with the system class loader
86       * @param deferTo delegate class loader to use for ignored packages
87       */
88      public ClassLoader(final java.lang.ClassLoader deferTo, final String[] ignoredPackages) {
89          this(ignoredPackages);
90          this.repository = new ClassLoaderRepository(deferTo);
91      }
92  
93      /**
94       * @param ignoredPackages classes contained in these packages will be loaded with the system class loader
95       */
96      public ClassLoader(final String[] ignoredPackages) {
97          this.ignoredPackages = ignoredPackages;
98      }
99  
100     /**
101      * Override this method to create you own classes on the fly. The name contains the special token $$BCEL$$. Everything
102      * before that token is considered to be a package name. You can encode your own arguments into the subsequent string.
103      * You must ensure however not to use any "illegal" characters, i.e., characters that may not appear in a Java class
104      * name too
105      * <p>
106      * The default implementation interprets the string as a encoded compressed Java class, unpacks and decodes it with the
107      * Utility.decode() method, and parses the resulting byte array and returns the resulting JavaClass object.
108      * </p>
109      *
110      * @param className compressed byte code with "$$BCEL$$" in it
111      */
112     protected JavaClass createClass(final String className) {
113         final int index = className.indexOf(BCEL_TOKEN);
114         final String realName = className.substring(index + BCEL_TOKEN.length());
115         JavaClass clazz = null;
116         try {
117             final byte[] bytes = Utility.decode(realName, true);
118             final ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo");
119             clazz = parser.parse();
120         } catch (final IOException e) {
121             e.printStackTrace();
122             return null;
123         }
124         // Adapt the class name to the passed value
125         final ConstantPool cp = clazz.getConstantPool();
126         final ConstantClass cl = cp.getConstant(clazz.getClassNameIndex(), Const.CONSTANT_Class, ConstantClass.class);
127         final ConstantUtf8 name = cp.getConstantUtf8(cl.getNameIndex());
128         name.setBytes(Utility.packageToPath(className));
129         return clazz;
130     }
131 
132     @Override
133     protected Class<?> loadClass(final String className, final boolean resolve) throws ClassNotFoundException {
134         Class<?> cl = null;
135         /*
136          * First try: lookup hash table.
137          */
138         if ((cl = classes.get(className)) == null) {
139             /*
140              * Second try: Load system class using system class loader. You better don't mess around with them.
141              */
142             for (final String ignoredPackage : ignoredPackages) {
143                 if (className.startsWith(ignoredPackage)) {
144                     cl = getParent().loadClass(className);
145                     break;
146                 }
147             }
148             if (cl == null) {
149                 JavaClass clazz = null;
150                 /*
151                  * Third try: Special request?
152                  */
153                 if (className.contains(BCEL_TOKEN)) {
154                     clazz = createClass(className);
155                 } else { // Fourth try: Load classes via repository
156                     if ((clazz = repository.loadClass(className)) == null) {
157                         throw new ClassNotFoundException(className);
158                     }
159                     clazz = modifyClass(clazz);
160                 }
161                 if (clazz != null) {
162                     final byte[] bytes = clazz.getBytes();
163                     cl = defineClass(className, bytes, 0, bytes.length);
164                 } else {
165                     cl = Class.forName(className);
166                 }
167             }
168             if (resolve) {
169                 resolveClass(cl);
170             }
171         }
172         classes.put(className, cl);
173         return cl;
174     }
175 
176     /**
177      * Override this method if you want to alter a class before it gets actually loaded. Does nothing by default.
178      */
179     protected JavaClass modifyClass(final JavaClass clazz) {
180         return clazz;
181     }
182 }