From 85386f41912c5c70f52995a20517cdd06bc62ce5 Mon Sep 17 00:00:00 2001 From: Volker Berlin Date: Thu, 2 Jan 2020 16:52:38 +0100 Subject: [PATCH] change the static ClassFile cache to an instance cache --- .../jwebassembly/module/ClassFileLoader.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/de/inetsoftware/jwebassembly/module/ClassFileLoader.java diff --git a/src/de/inetsoftware/jwebassembly/module/ClassFileLoader.java b/src/de/inetsoftware/jwebassembly/module/ClassFileLoader.java new file mode 100644 index 0000000..cbe9b42 --- /dev/null +++ b/src/de/inetsoftware/jwebassembly/module/ClassFileLoader.java @@ -0,0 +1,71 @@ +/* + Copyright 2020 Volker Berlin (i-net software) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ +package de.inetsoftware.jwebassembly.module; + +import java.io.IOException; +import java.io.InputStream; + +import javax.annotation.Nullable; + +import de.inetsoftware.classparser.ClassFile; +import de.inetsoftware.classparser.WeakValueCache; + +/** + * Cache and manager for the loaded ClassFiles + * + * @author Volker Berlin + */ +public class ClassFileLoader { + + private final WeakValueCache CACHE = new WeakValueCache<>(); + + private final ClassLoader loader; + + /** + * Create a new instance + * + * @param loader + * the classloader to find the *.class files + */ + public ClassFileLoader( ClassLoader loader ) { + this.loader = loader; + } + + /** + * Get the ClassFile from cache or load it. + * + * @param className + * the class name + * @return the ClassFile or null + * @throws IOException + * If any I/O error occur + */ + @Nullable + public ClassFile get( String className ) throws IOException { + ClassFile classFile = CACHE.get( className ); + if( classFile != null ) { + return classFile; + } + InputStream stream = loader.getResourceAsStream( className + ".class" ); + if( stream != null ) { + classFile = new ClassFile( stream ); + CACHE.put( className, classFile ); + } + return classFile; + } + +}