Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/src/jdk/internal/dynalink/beans/AccessibleMembersLookup.java
48549 views
/*1* Copyright (c) 2010, 2013, 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. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file, and Oracle licenses the original version of this file under the BSD30* license:31*/32/*33Copyright 2009-2013 Attila Szegedi3435Licensed under both the Apache License, Version 2.0 (the "Apache License")36and the BSD License (the "BSD License"), with licensee being free to37choose either of the two at their discretion.3839You may not use this file except in compliance with either the Apache40License or the BSD License.4142If you choose to use this file in compliance with the Apache License, the43following notice applies to you:4445You may obtain a copy of the Apache License at4647http://www.apache.org/licenses/LICENSE-2.04849Unless required by applicable law or agreed to in writing, software50distributed under the License is distributed on an "AS IS" BASIS,51WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or52implied. See the License for the specific language governing53permissions and limitations under the License.5455If you choose to use this file in compliance with the BSD License, the56following notice applies to you:5758Redistribution and use in source and binary forms, with or without59modification, are permitted provided that the following conditions are60met:61* Redistributions of source code must retain the above copyright62notice, this list of conditions and the following disclaimer.63* Redistributions in binary form must reproduce the above copyright64notice, this list of conditions and the following disclaimer in the65documentation and/or other materials provided with the distribution.66* Neither the name of the copyright holder nor the names of67contributors may be used to endorse or promote products derived from68this software without specific prior written permission.6970THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS71IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED72TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A73PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER74BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR75CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF76SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR77BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,78WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR79OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF80ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.81*/8283package jdk.internal.dynalink.beans;8485import java.lang.reflect.Method;86import java.lang.reflect.Modifier;87import java.util.Arrays;88import java.util.Collection;89import java.util.HashMap;90import java.util.LinkedHashSet;91import java.util.Map;92import java.util.Set;9394/**95* Utility class for discovering accessible methods and inner classes. Normally, a public member declared on a class is96* accessible (that is, it can be invoked from anywhere). However, this is not the case if the class itself is not97* public, or belongs to a restricted-access package. In that case, it is required to lookup a member in a publicly98* accessible superclass or implemented interface of the class, and use it instead of the member discovered on the99* class.100*101* @author Attila Szegedi102*/103class AccessibleMembersLookup {104private final Map<MethodSignature, Method> methods;105private final Set<Class<?>> innerClasses;106private final boolean instance;107108/**109* Creates a mapping for all accessible methods and inner classes on a class.110*111* @param clazz the inspected class112* @param instance true to inspect instance methods, false to inspect static methods.113*/114AccessibleMembersLookup(final Class<?> clazz, final boolean instance) {115this.methods = new HashMap<>();116this.innerClasses = new LinkedHashSet<>();117this.instance = instance;118lookupAccessibleMembers(clazz);119}120121/**122* Returns an accessible method equivalent of a method.123*124* @param m the method whose accessible equivalent is requested.125* @return the accessible equivalent for the method (can be the same as the passed in method), or null if there is126* no accessible method equivalent.127*/128Method getAccessibleMethod(final Method m) {129return m == null ? null : methods.get(new MethodSignature(m));130}131132Collection<Method> getMethods() {133return methods.values();134}135136Class<?>[] getInnerClasses() {137return innerClasses.toArray(new Class<?>[innerClasses.size()]);138}139140/**141* A helper class that represents a method signature - name and argument types.142*143* @author Attila Szegedi144*/145static final class MethodSignature {146private final String name;147private final Class<?>[] args;148149/**150* Creates a new method signature from arbitrary data.151*152* @param name the name of the method this signature represents.153* @param args the argument types of the method.154*/155MethodSignature(final String name, final Class<?>[] args) {156this.name = name;157this.args = args;158}159160/**161* Creates a signature for the given method.162*163* @param method the method for which a signature is created.164*/165MethodSignature(final Method method) {166this(method.getName(), method.getParameterTypes());167}168169/**170* Compares this object to another object171*172* @param o the other object173* @return true if the other object is also a method signature with the same name, same number of arguments, and174* same types of arguments.175*/176@Override177public boolean equals(final Object o) {178if(o instanceof MethodSignature) {179final MethodSignature ms = (MethodSignature)o;180return ms.name.equals(name) && Arrays.equals(args, ms.args);181}182return false;183}184185/**186* Returns a hash code, consistent with the overridden {@link #equals(Object)}.187*/188@Override189public int hashCode() {190return name.hashCode() ^ Arrays.hashCode(args);191}192193@Override194public String toString() {195final StringBuilder b = new StringBuilder();196b.append("[MethodSignature ").append(name).append('(');197if(args.length > 0) {198b.append(args[0].getCanonicalName());199for(int i = 1; i < args.length; ++i) {200b.append(", ").append(args[i].getCanonicalName());201}202}203return b.append(")]").toString();204}205}206207private void lookupAccessibleMembers(final Class<?> clazz) {208boolean searchSuperTypes;209210if(!CheckRestrictedPackage.isRestrictedClass(clazz)) {211searchSuperTypes = false;212for(final Method method: clazz.getMethods()) {213final boolean isStatic = Modifier.isStatic(method.getModifiers());214if(instance != isStatic) {215final MethodSignature sig = new MethodSignature(method);216if(!methods.containsKey(sig)) {217final Class<?> declaringClass = method.getDeclaringClass();218if(declaringClass != clazz && CheckRestrictedPackage.isRestrictedClass(declaringClass)) {219//Sometimes, the declaring class of a method (Method.getDeclaringClass())220//retrieved through Class.getMethods() for a public class will be a221//non-public superclass. For such a method, we need to find a method with222//the same name and signature in a public superclass or implemented223//interface.224//This typically doesn't happen with classes emitted by a reasonably modern225//javac, as it'll create synthetic delegator methods in all public226//immediate subclasses of the non-public class. We have, however, observed227//this in the wild with class files compiled with older javac that doesn't228//generate the said synthetic delegators.229searchSuperTypes = true;230} else {231// don't allow inherited static232if (!isStatic || clazz == declaringClass) {233methods.put(sig, method);234}235}236}237}238}239for(final Class<?> innerClass: clazz.getClasses()) {240// Add both static and non-static classes, regardless of instance flag. StaticClassLinker will just241// expose non-static classes with explicit constructor outer class argument.242// NOTE: getting inner class objects through getClasses() does not resolve them, so if those classes243// were not yet loaded, they'll only get loaded in a non-resolved state; no static initializers for244// them will trigger just by doing this.245innerClasses.add(innerClass);246}247} else {248searchSuperTypes = true;249}250251// don't need to search super types for static methods252if(instance && searchSuperTypes) {253// If we reach here, the class is either not public, or it is in a restricted package. Alternatively, it is254// public, but some of its methods claim that their declaring class is non-public. We'll try superclasses255// and implemented interfaces then looking for public ones.256final Class<?>[] interfaces = clazz.getInterfaces();257for(int i = 0; i < interfaces.length; i++) {258lookupAccessibleMembers(interfaces[i]);259}260final Class<?> superclass = clazz.getSuperclass();261if(superclass != null) {262lookupAccessibleMembers(superclass);263}264}265}266}267268269