View Javadoc

1   /*
2    * $Id$
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  package org.apache.struts2.compiler;
22  
23  import java.util.Map;
24  import java.util.concurrent.ConcurrentHashMap;
25  
26  /***
27   * Keeps a cache of class name -> MemoryJavaFileObject. If the requested class name is in the cache
28   * a new class is defined for it, otherwise findClass delegates to the parent class loader
29   */
30  public class MemoryClassLoader extends ClassLoader {
31      private Map<String, MemoryJavaFileObject> cachedObjects = new ConcurrentHashMap<String, MemoryJavaFileObject>();
32  
33      public MemoryClassLoader() {
34          //without this, the tests will not run, because the tests are loaded by a custom classloader
35          //so the classes referenced from the compiled code will not be found by the System Class Loader because
36          //the target dir is not part of the classpath used when calling the jvm to execute the tests
37          super(Thread.currentThread().getContextClassLoader());
38      }
39  
40      @Override
41      protected Class<?> findClass(String name) throws
42              ClassNotFoundException {
43          MemoryJavaFileObject fileObject = cachedObjects.get(name);
44          if (fileObject != null) {
45              byte[] bytes = fileObject.toByteArray();
46              return defineClass(name, bytes, 0, bytes.length);
47          }
48          return super.findClass(name);
49      }
50  
51      public void addMemoryJavaFileObject(String jsp, MemoryJavaFileObject memoryJavaFileObject) {
52          cachedObjects.put(jsp, memoryJavaFileObject);
53      }
54  }