Path: blob/master/test/hotspot/jtreg/runtime/LoaderConstraints/ldrCnstrFldMsg/pkg/ClassLoaderForParentFoo.java
41155 views
/*1* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324package pkg;2526import java.util.*;27import java.io.*;2829// This class loader loads Foo and Parent and calls back to l1 to load Grand.30public class ClassLoaderForParentFoo extends ClassLoader {3132private final Set<String> names = new HashSet<>();3334ClassLoader l1;3536public ClassLoaderForParentFoo(ClassLoader l, String... names) {37l1 = l;38for (String n : names) this.names.add(n);39}4041protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {42if (name.contains("Grand")) return l1.loadClass("pkg.Grand");43if (!names.contains(name)) return super.loadClass(name, resolve);44Class<?> result = findLoadedClass(name);45if (result == null) {46// Load our own version of Foo that will be referenced by Parent.47if (name.contains("Parent")) loadClass("pkg.Foo", resolve);48String filename = name.replace('.', '/') + ".class";49try (InputStream data = getResourceAsStream(filename)) {50if (data == null) throw new ClassNotFoundException();51try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {52int b;53do {54b = data.read();55if (b >= 0) buffer.write(b);56} while (b >= 0);57byte[] bytes = buffer.toByteArray();58result = defineClass(name, bytes, 0, bytes.length);59}60} catch (IOException e) {61throw new ClassNotFoundException("Error reading class file", e);62}63}64if (resolve) resolveClass(result);65return result;66}6768}697071