jdk
1/*
2* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
3* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4*
5* This code is free software; you can redistribute it and/or modify it
6* under the terms of the GNU General Public License version 2 only, as
7* published by the Free Software Foundation.
8*
9* This code is distributed in the hope that it will be useful, but WITHOUT
10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12* version 2 for more details (a copy is included in the LICENSE file that
13* accompanied this code).
14*
15* You should have received a copy of the GNU General Public License version
16* 2 along with this work; if not, write to the Free Software Foundation,
17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18*
19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20* or visit www.oracle.com if you need additional information or have any
21* questions.
22*/
23
24import java.io.*;25import java.net.URI;26import java.util.HashMap;27import java.util.Map;28import javax.tools.*;29
30import static java.util.Collections.unmodifiableMap;31
32/**
33* class for storing source/byte code in memory.
34*/
35public class InMemoryFileManager extends ForwardingJavaFileManager {36
37private final Map<String, InMemoryJavaFile> classes = new HashMap<>();38
39public InMemoryFileManager(JavaFileManager fileManager) {40super(fileManager);41}42
43@Override44public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException {45
46InMemoryJavaFile javaFile = new InMemoryJavaFile(className);47classes.put(className, javaFile);48return javaFile;49}50
51@Override52public ClassLoader getClassLoader(Location location) {53return new ClassLoader(this.getClass().getClassLoader()) {54@Override55protected Class<?> findClass(String name) throws ClassNotFoundException {56InMemoryJavaFile classData = classes.get(name);57if (classData == null) throw new ClassNotFoundException(name);58byte[] byteCode = classData.bos.toByteArray();59return defineClass(name, byteCode, 0, byteCode.length);60}61};62}63
64public Map<String, ? extends JavaFileObject> getClasses() {65return unmodifiableMap(classes);66}67
68private static class InMemoryJavaFile extends SimpleJavaFileObject {69
70private final ByteArrayOutputStream bos =71new ByteArrayOutputStream();72
73
74protected InMemoryJavaFile(String name) {75super(URI.create("mfm:///" + name.replace('.', '/') + Kind.CLASS.extension), Kind.CLASS);76}77
78@Override79public OutputStream openOutputStream() throws IOException {80return bos;81}82
83@Override84public InputStream openInputStream() throws IOException {85return new ByteArrayInputStream(bos.toByteArray());86}87}88}
89