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.io.ByteArrayInputStream; 023 import java.io.InputStream; 024 import java.net.URL; 025 import java.net.URLClassLoader; 026 import java.util.List; 027 import java.util.jar.Manifest; 028 029 public class GeneratedClassLoader extends URLClassLoader { 030 private ClassFileFactory factory; 031 032 public GeneratedClassLoader(@NotNull ClassFileFactory factory, ClassLoader parentClassLoader, URL... urls) { 033 super(urls, parentClassLoader); 034 this.factory = factory; 035 } 036 037 @Override 038 public InputStream getResourceAsStream(String name) { 039 OutputFile outputFile = factory.get(name); 040 if (outputFile != null) { 041 return new ByteArrayInputStream(outputFile.asByteArray()); 042 } 043 return super.getResourceAsStream(name); 044 } 045 046 @NotNull 047 @Override 048 protected Class<?> findClass(@NotNull String name) throws ClassNotFoundException { 049 String classFilePath = name.replace('.', '/') + ".class"; 050 051 OutputFile outputFile = factory.get(classFilePath); 052 if (outputFile != null) { 053 byte[] bytes = outputFile.asByteArray(); 054 int lastDot = name.lastIndexOf('.'); 055 if (lastDot >= 0) { 056 String pkgName = name.substring(0, lastDot); 057 if (getPackage(pkgName) == null) { 058 definePackage(pkgName, new Manifest(), null); 059 } 060 } 061 return defineClass(name, bytes, 0, bytes.length); 062 } 063 064 return super.findClass(name); 065 } 066 067 public void dispose() { 068 factory = null; 069 } 070 071 @NotNull 072 public List<OutputFile> getAllGeneratedFiles() { 073 return factory.asList(); 074 } 075 }