001    /*
002     * Copyright 2010-2015 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.kotlin.codegen;
018    
019    import org.jetbrains.annotations.NotNull;
020    import org.jetbrains.kotlin.backend.common.output.OutputFile;
021    
022    import java.net.URL;
023    import java.net.URLClassLoader;
024    import java.util.List;
025    import java.util.jar.Manifest;
026    
027    public class GeneratedClassLoader extends URLClassLoader {
028        private ClassFileFactory state;
029    
030        public GeneratedClassLoader(@NotNull ClassFileFactory state, ClassLoader parentClassLoader, URL...urls) {
031            super(urls, parentClassLoader);
032            this.state = state;
033        }
034    
035        @NotNull
036        @Override
037        protected Class<?> findClass(@NotNull String name) throws ClassNotFoundException {
038            String classFilePath = name.replace('.', '/') + ".class";
039    
040            OutputFile outputFile = state.get(classFilePath);
041            if (outputFile != null) {
042                byte[] bytes = outputFile.asByteArray();
043                int lastDot = name.lastIndexOf('.');
044                if (lastDot >= 0) {
045                    String pkgName = name.substring(0, lastDot);
046                    if (getPackage(pkgName) == null) {
047                        definePackage(pkgName, new Manifest(), null);
048                    }
049                }
050                return defineClass(name, bytes, 0, bytes.length);
051            }
052    
053            return super.findClass(name);
054        }
055    
056        public void dispose() {
057            state = null;
058        }
059    
060        @NotNull
061        public List<OutputFile> getAllGeneratedFiles() {
062            return state.asList();
063        }
064    }