Path: blob/master/test/hotspot/jtreg/runtime/HiddenClasses/CastToParentTest.java
40942 views
/*1* Copyright (c) 2020, 2021, 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*/2223/*24* @test25* @summary Test that a hidden class can be cast to its parent.26* DESCRIPTION27* Try to cast an object of a hidden class to its parent (called CastToParentTest)28* - (CastToParentTest) o29* - o.getClass().cast(<hiddenClassObj>);30* and cast to its grandparent (java.lang.Object).31*32* @library /test/lib33* @modules jdk.compiler34* @run main CastToParentTest35*/3637import java.lang.invoke.MethodType;38import java.lang.invoke.MethodHandles;39import java.lang.invoke.MethodHandles.Lookup;40import static java.lang.invoke.MethodHandles.Lookup.ClassOption.*;41import jdk.test.lib.compiler.InMemoryJavaCompiler;4243public class CastToParentTest {4445static byte klassbuf[] = InMemoryJavaCompiler.compile("TestClass",46"public class TestClass extends CastToParentTest { " +47" public static void concat(String one, String two) throws Throwable { " +48" System.out.println(one + two);" +49" } } ");5051public static void main(String[] args) throws Throwable {52Lookup lookup = MethodHandles.lookup();53Class<?> c = lookup.defineHiddenClass(klassbuf, false, NESTMATE).lookupClass();54Object hiddenClassObj = c.newInstance();5556// Cast hidden class to its parent.57CastToParentTest parentObj = (CastToParentTest)hiddenClassObj;5859if (!parentObj.equals(hiddenClassObj)) {60throw new RuntimeException("Hidden class object cannot be cast to parent");61}6263// Try to cast using a different mechanism.64new CastToParentTest().getClass().cast(hiddenClassObj);656667// Cast hidden class to its grandparent.68java.lang.Object grandparentObj = (java.lang.Object)hiddenClassObj;6970if (!grandparentObj.equals(hiddenClassObj)) {71throw new RuntimeException("Hidden class object cannot be cast to grandparent");72}7374// Try to cast using a different mechanism.75new java.lang.Object().getClass().cast(hiddenClassObj);76}7778}798081