Path: blob/master/src/jdk.dynalink/share/classes/jdk/dynalink/beans/AccessibleMembersLookup.java
41161 views
/*1* Copyright (c) 2010, 2016, 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 Szegedi3435Redistribution and use in source and binary forms, with or without36modification, are permitted provided that the following conditions are37met:38* Redistributions of source code must retain the above copyright39notice, this list of conditions and the following disclaimer.40* Redistributions in binary form must reproduce the above copyright41notice, this list of conditions and the following disclaimer in the42documentation and/or other materials provided with the distribution.43* Neither the name of the copyright holder nor the names of44contributors may be used to endorse or promote products derived from45this software without specific prior written permission.4647THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS48IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED49TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A50PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER51BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR52CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF53SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR54BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,55WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR56OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF57ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.58*/5960package jdk.dynalink.beans;6162import java.lang.reflect.Method;63import java.lang.reflect.Modifier;64import java.util.Arrays;65import java.util.Collection;66import java.util.HashMap;67import java.util.LinkedHashMap;68import java.util.Map;6970/**71* Utility class for discovering accessible methods and inner classes. Normally, a public member declared on a class is72* accessible (that is, it can be invoked from anywhere). However, this is not the case if the class itself is not73* public, or belongs to a restricted-access package. In that case, it is required to lookup a member in a publicly74* accessible superclass or implemented interface of the class, and use it instead of the member discovered on the75* class.76*/77class AccessibleMembersLookup {78private final Map<MethodSignature, Method> methods;79private final Map<String, Class<?>> innerClasses;80private final boolean instance;8182/**83* Creates a mapping for all accessible methods and inner classes on a class.84*85* @param clazz the inspected class86* @param instance true to inspect instance methods, false to inspect static methods.87*/88AccessibleMembersLookup(final Class<?> clazz, final boolean instance) {89this.methods = new HashMap<>();90this.innerClasses = new LinkedHashMap<>();91this.instance = instance;92lookupAccessibleMembers(clazz);93}9495Collection<Method> getMethods() {96return methods.values();97}9899Class<?>[] getInnerClasses() {100return innerClasses.values().toArray(new Class<?>[0]);101}102103Method getAccessibleMethod(final Method m) {104return methods.get(new MethodSignature(m));105}106107/**108* A helper class that represents a method signature - name and argument types.109*/110static final class MethodSignature {111private final String name;112private final Class<?>[] args;113114/**115* Creates a new method signature from arbitrary data.116*117* @param name the name of the method this signature represents.118* @param args the argument types of the method.119*/120MethodSignature(final String name, final Class<?>[] args) {121this.name = name;122this.args = args;123}124125/**126* Creates a signature for the given method.127*128* @param method the method for which a signature is created.129*/130MethodSignature(final Method method) {131this(method.getName(), method.getParameterTypes());132}133134/**135* Compares this object to another object136*137* @param o the other object138* @return true if the other object is also a method signature with the same name, same number of arguments, and139* same types of arguments.140*/141@Override142public boolean equals(final Object o) {143if(o instanceof MethodSignature) {144final MethodSignature ms = (MethodSignature)o;145return ms.name.equals(name) && Arrays.equals(args, ms.args);146}147return false;148}149150/**151* Returns a hash code, consistent with the overridden {@link #equals(Object)}.152*/153@Override154public int hashCode() {155return name.hashCode() ^ Arrays.hashCode(args);156}157158@Override159public String toString() {160final StringBuilder b = new StringBuilder();161b.append("[MethodSignature ").append(name).append('(');162if(args.length > 0) {163b.append(args[0].getCanonicalName());164for(int i = 1; i < args.length; ++i) {165b.append(", ").append(args[i].getCanonicalName());166}167}168return b.append(")]").toString();169}170}171172private void lookupAccessibleMembers(final Class<?> clazz) {173boolean searchSuperTypes;174175if(!CheckRestrictedPackage.isRestrictedClass(clazz)) {176searchSuperTypes = false;177for(final Method method: clazz.getMethods()) {178final boolean isStatic = Modifier.isStatic(method.getModifiers());179if(instance != isStatic) {180final MethodSignature sig = new MethodSignature(method);181if(!methods.containsKey(sig)) {182final Class<?> declaringClass = method.getDeclaringClass();183if(declaringClass != clazz && CheckRestrictedPackage.isRestrictedClass(declaringClass)) {184//Sometimes, the declaring class of a method (Method.getDeclaringClass())185//retrieved through Class.getMethods() for a public class will be a186//non-public superclass. For such a method, we need to find a method with187//the same name and signature in a public superclass or implemented188//interface.189//This typically doesn't happen with classes emitted by a reasonably modern190//javac, as it'll create synthetic delegator methods in all public191//immediate subclasses of the non-public class. We have, however, observed192//this in the wild with class files compiled with older javac that doesn't193//generate the said synthetic delegators.194searchSuperTypes = true;195} else {196// don't allow inherited static197if (!isStatic || clazz == declaringClass) {198methods.put(sig, method);199}200}201}202}203}204for(final Class<?> innerClass: clazz.getClasses()) {205// Add both static and non-static classes, regardless of instance flag. StaticClassLinker will just206// expose non-static classes with explicit constructor outer class argument.207// NOTE: getting inner class objects through getClasses() does not resolve them, so if those classes208// were not yet loaded, they'll only get loaded in a non-resolved state; no static initializers for209// them will trigger just by doing this.210// Don't overwrite an inner class with an inherited inner class with the same name.211Class<?> previousClass = innerClasses.get(innerClass.getSimpleName());212if (previousClass == null || previousClass.getDeclaringClass().isAssignableFrom(innerClass.getDeclaringClass())) {213innerClasses.put(innerClass.getSimpleName(), innerClass);214}215}216} else {217searchSuperTypes = true;218}219220// don't need to search super types for static methods221if(instance && searchSuperTypes) {222// If we reach here, the class is either not public, or it is in a restricted package. Alternatively, it is223// public, but some of its methods claim that their declaring class is non-public. We'll try superclasses224// and implemented interfaces then looking for public ones.225for (final Class<?> itf: clazz.getInterfaces()) {226lookupAccessibleMembers(itf);227}228final Class<?> superclass = clazz.getSuperclass();229if(superclass != null) {230lookupAccessibleMembers(superclass);231}232}233}234}235236237