1 /* 2 * Copyright (c) 2020, 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 24 /* 25 * @test 26 * @summary Test issues with instantiating hidden classes. 27 * @library /test/lib 28 * @modules jdk.compiler 29 * @run main InstantiateHiddenClass 30 */ 31 32 import java.lang.invoke.MethodType; 33 import java.lang.invoke.MethodHandles; 34 import java.lang.invoke.MethodHandles.Lookup; 35 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.*; 36 import jdk.test.lib.compiler.InMemoryJavaCompiler; 37 38 public class InstantiateHiddenClass { 39 40 static byte klassbuf[] = InMemoryJavaCompiler.compile("TestClass", 41 "public class TestClass { " + 42 " public static void concat(String one, String two) throws Throwable { " + 43 " System.out.println(one + two);" + 44 " } } "); 45 46 public static void main(String[] args) throws Throwable { 47 48 // Test that a hidden class cannot be found through its name. 49 try { 50 Lookup lookup = MethodHandles.lookup(); 51 Class<?> cl = lookup.defineHiddenClass(klassbuf, false, NESTMATE).lookupClass(); 52 Class.forName(cl.getName()).newInstance(); 53 throw new RuntimeException("Expected ClassNotFoundException not thrown"); 54 } catch (ClassNotFoundException e ) { 55 // Test passed 56 } 57 58 59 // Create two hidden classes and instantiate an object from each of them. 60 // Verify that the references to these objects are different and references 61 // to their classes are not equal either. 62 Lookup lookup = MethodHandles.lookup(); 63 Class<?> c1 = lookup.defineHiddenClass(klassbuf, false, NESTMATE).lookupClass(); 64 Class<?> c2 = lookup.defineHiddenClass(klassbuf, false, NESTMATE).lookupClass(); 65 Object o1 = c1.newInstance(); 66 Object o2 = c2.newInstance(); 67 if (o1 == o2) { 68 throw new RuntimeException("Objects should not be equal"); 69 } 70 if (o1.getClass() == o2.getClass()) { 71 throw new RuntimeException("Classes should not be equal"); 72 } 73 } 74 }