Introspector.java 63.1 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27
 */

package java.beans;

28
import com.sun.beans.TypeResolver;
29
import com.sun.beans.WeakCache;
D
duke 已提交
30
import com.sun.beans.finder.ClassFinder;
31
import com.sun.beans.finder.MethodFinder;
D
duke 已提交
32

33 34
import java.awt.Component;

35 36
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
D
duke 已提交
37 38
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
39
import java.lang.reflect.Type;
D
duke 已提交
40 41 42 43 44 45

import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.EventListener;
46
import java.util.EventObject;
D
duke 已提交
47 48
import java.util.List;
import java.util.TreeMap;
49

D
duke 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
import sun.reflect.misc.ReflectUtil;

/**
 * The Introspector class provides a standard way for tools to learn about
 * the properties, events, and methods supported by a target Java Bean.
 * <p>
 * For each of those three kinds of information, the Introspector will
 * separately analyze the bean's class and superclasses looking for
 * either explicit or implicit information and use that information to
 * build a BeanInfo object that comprehensively describes the target bean.
 * <p>
 * For each class "Foo", explicit information may be available if there exists
 * a corresponding "FooBeanInfo" class that provides a non-null value when
 * queried for the information.   We first look for the BeanInfo class by
 * taking the full package-qualified name of the target bean class and
 * appending "BeanInfo" to form a new class name.  If this fails, then
 * we take the final classname component of this name, and look for that
 * class in each of the packages specified in the BeanInfo package search
 * path.
 * <p>
 * Thus for a class such as "sun.xyz.OurButton" we would first look for a
 * BeanInfo class called "sun.xyz.OurButtonBeanInfo" and if that failed we'd
 * look in each package in the BeanInfo search path for an OurButtonBeanInfo
 * class.  With the default search path, this would mean looking for
 * "sun.beans.infos.OurButtonBeanInfo".
 * <p>
 * If a class provides explicit BeanInfo about itself then we add that to
 * the BeanInfo information we obtained from analyzing any derived classes,
 * but we regard the explicit information as being definitive for the current
 * class and its base classes, and do not proceed any further up the superclass
 * chain.
 * <p>
 * If we don't find explicit BeanInfo on a class, we use low-level
 * reflection to study the methods of the class and apply standard design
 * patterns to identify property accessors, event sources, or public
 * methods.  We then proceed to analyze the class's superclass and add
 * in the information from it (and possibly on up the superclass chain).
 * <p>
 * For more information about introspection and design patterns, please
 * consult the
90
 *  <a href="http://java.sun.com/products/javabeans/docs/index.html">JavaBeans&trade; specification</a>.
D
duke 已提交
91 92 93 94 95
 */

public class Introspector {

    // Flags that can be used to control getBeanInfo:
96 97 98
    /**
     * Flag to indicate to use of all beaninfo.
     */
D
duke 已提交
99
    public final static int USE_ALL_BEANINFO           = 1;
100 101 102
    /**
     * Flag to indicate to ignore immediate beaninfo.
     */
D
duke 已提交
103
    public final static int IGNORE_IMMEDIATE_BEANINFO  = 2;
104 105 106
    /**
     * Flag to indicate to ignore all beaninfo.
     */
D
duke 已提交
107 108 109
    public final static int IGNORE_ALL_BEANINFO        = 3;

    // Static Caches to speed up introspection.
110
    private static final WeakCache<Class<?>, Method[]> declaredMethodCache = new WeakCache<>();
D
duke 已提交
111

112
    private Class<?> beanClass;
D
duke 已提交
113 114 115 116 117
    private BeanInfo explicitBeanInfo;
    private BeanInfo superBeanInfo;
    private BeanInfo additionalBeanInfo[];

    private boolean propertyChangeSource = false;
118
    private static Class<EventListener> eventListenerType = EventListener.class;
D
duke 已提交
119 120 121 122 123 124 125

    // These should be removed.
    private String defaultEventName;
    private String defaultPropertyName;
    private int defaultEventIndex = -1;
    private int defaultPropertyIndex = -1;

126 127
    // Methods maps from Method names to MethodDescriptors
    private Map<String, MethodDescriptor> methods;
D
duke 已提交
128 129

    // properties maps from String names to PropertyDescriptors
130
    private Map<String, PropertyDescriptor> properties;
D
duke 已提交
131 132

    // events maps from String names to EventSetDescriptors
133
    private Map<String, EventSetDescriptor> events;
D
duke 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

    private final static EventSetDescriptor[] EMPTY_EVENTSETDESCRIPTORS = new EventSetDescriptor[0];

    static final String ADD_PREFIX = "add";
    static final String REMOVE_PREFIX = "remove";
    static final String GET_PREFIX = "get";
    static final String SET_PREFIX = "set";
    static final String IS_PREFIX = "is";

    //======================================================================
    //                          Public methods
    //======================================================================

    /**
     * Introspect on a Java Bean and learn about all its properties, exposed
     * methods, and events.
     * <p>
     * If the BeanInfo class for a Java Bean has been previously Introspected
     * then the BeanInfo class is retrieved from the BeanInfo cache.
     *
     * @param beanClass  The bean class to be analyzed.
     * @return  A BeanInfo object describing the target bean.
     * @exception IntrospectionException if an exception occurs during
     *              introspection.
     * @see #flushCaches
     * @see #flushFromCaches
     */
    public static BeanInfo getBeanInfo(Class<?> beanClass)
        throws IntrospectionException
    {
        if (!ReflectUtil.isPackageAccessible(beanClass)) {
            return (new Introspector(beanClass, null, USE_ALL_BEANINFO)).getBeanInfo();
        }
167
        ThreadGroupContext context = ThreadGroupContext.getContext();
168
        BeanInfo beanInfo;
169 170
        synchronized (declaredMethodCache) {
            beanInfo = context.getBeanInfo(beanClass);
171 172 173
        }
        if (beanInfo == null) {
            beanInfo = new Introspector(beanClass, null, USE_ALL_BEANINFO).getBeanInfo();
174 175
            synchronized (declaredMethodCache) {
                context.putBeanInfo(beanClass, beanInfo);
176
            }
177
        }
178
        return beanInfo;
D
duke 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    }

    /**
     * Introspect on a Java bean and learn about all its properties, exposed
     * methods, and events, subject to some control flags.
     * <p>
     * If the BeanInfo class for a Java Bean has been previously Introspected
     * based on the same arguments then the BeanInfo class is retrieved
     * from the BeanInfo cache.
     *
     * @param beanClass  The bean class to be analyzed.
     * @param flags  Flags to control the introspection.
     *     If flags == USE_ALL_BEANINFO then we use all of the BeanInfo
     *          classes we can discover.
     *     If flags == IGNORE_IMMEDIATE_BEANINFO then we ignore any
     *           BeanInfo associated with the specified beanClass.
     *     If flags == IGNORE_ALL_BEANINFO then we ignore all BeanInfo
     *           associated with the specified beanClass or any of its
     *           parent classes.
     * @return  A BeanInfo object describing the target bean.
     * @exception IntrospectionException if an exception occurs during
     *              introspection.
     */
    public static BeanInfo getBeanInfo(Class<?> beanClass, int flags)
                                                throws IntrospectionException {
        return getBeanInfo(beanClass, null, flags);
    }

    /**
     * Introspect on a Java bean and learn all about its properties, exposed
     * methods, below a given "stop" point.
     * <p>
     * If the BeanInfo class for a Java Bean has been previously Introspected
     * based on the same arguments, then the BeanInfo class is retrieved
     * from the BeanInfo cache.
214
     * @return the BeanInfo for the bean
D
duke 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
     * @param beanClass The bean class to be analyzed.
     * @param stopClass The baseclass at which to stop the analysis.  Any
     *    methods/properties/events in the stopClass or in its baseclasses
     *    will be ignored in the analysis.
     * @exception IntrospectionException if an exception occurs during
     *              introspection.
     */
    public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass)
                                                throws IntrospectionException {
        return getBeanInfo(beanClass, stopClass, USE_ALL_BEANINFO);
    }

    /**
     * Introspect on a Java Bean and learn about all its properties,
     * exposed methods and events, below a given {@code stopClass} point
     * subject to some control {@code flags}.
     * <dl>
     *  <dt>USE_ALL_BEANINFO</dt>
     *  <dd>Any BeanInfo that can be discovered will be used.</dd>
     *  <dt>IGNORE_IMMEDIATE_BEANINFO</dt>
     *  <dd>Any BeanInfo associated with the specified {@code beanClass} will be ignored.</dd>
     *  <dt>IGNORE_ALL_BEANINFO</dt>
     *  <dd>Any BeanInfo associated with the specified {@code beanClass}
     *      or any of its parent classes will be ignored.</dd>
     * </dl>
     * Any methods/properties/events in the {@code stopClass}
     * or in its parent classes will be ignored in the analysis.
     * <p>
     * If the BeanInfo class for a Java Bean has been
     * previously introspected based on the same arguments then
     * the BeanInfo class is retrieved from the BeanInfo cache.
     *
     * @param beanClass  the bean class to be analyzed
     * @param stopClass  the parent class at which to stop the analysis
     * @param flags      flags to control the introspection
     * @return a BeanInfo object describing the target bean
     * @exception IntrospectionException if an exception occurs during introspection
     *
     * @since 1.7
     */
    public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass,
                                        int flags) throws IntrospectionException {
        BeanInfo bi;
        if (stopClass == null && flags == USE_ALL_BEANINFO) {
            // Same parameters to take advantage of caching.
            bi = getBeanInfo(beanClass);
        } else {
            bi = (new Introspector(beanClass, stopClass, flags)).getBeanInfo();
        }
        return bi;

        // Old behaviour: Make an independent copy of the BeanInfo.
        //return new GenericBeanInfo(bi);
    }


    /**
     * Utility method to take a string and convert it to normal Java variable
     * name capitalization.  This normally means converting the first
     * character from upper case to lower case, but in the (unusual) special
     * case when there is more than one character and both the first and
     * second characters are upper case, we leave it alone.
     * <p>
     * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays
     * as "URL".
     *
     * @param  name The string to be decapitalized.
     * @return  The decapitalized version of the string.
     */
    public static String decapitalize(String name) {
        if (name == null || name.length() == 0) {
            return name;
        }
        if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
                        Character.isUpperCase(name.charAt(0))){
            return name;
        }
        char chars[] = name.toCharArray();
        chars[0] = Character.toLowerCase(chars[0]);
        return new String(chars);
    }

    /**
     * Gets the list of package names that will be used for
     *          finding BeanInfo classes.
     *
     * @return  The array of package names that will be searched in
     *          order to find BeanInfo classes. The default value
     *          for this array is implementation-dependent; e.g.
     *          Sun implementation initially sets to {"sun.beans.infos"}.
     */

307
    public static String[] getBeanInfoSearchPath() {
308
        return ThreadGroupContext.getContext().getBeanInfoFinder().getPackages();
D
duke 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    }

    /**
     * Change the list of package names that will be used for
     *          finding BeanInfo classes.  The behaviour of
     *          this method is undefined if parameter path
     *          is null.
     *
     * <p>First, if there is a security manager, its <code>checkPropertiesAccess</code>
     * method is called. This could result in a SecurityException.
     *
     * @param path  Array of package names.
     * @exception  SecurityException  if a security manager exists and its
     *             <code>checkPropertiesAccess</code> method doesn't allow setting
     *              of system properties.
     * @see SecurityManager#checkPropertiesAccess
     */

327
    public static void setBeanInfoSearchPath(String[] path) {
D
duke 已提交
328 329 330 331
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPropertiesAccess();
        }
332
        ThreadGroupContext.getContext().getBeanInfoFinder().setPackages(path);
D
duke 已提交
333 334 335 336 337 338 339 340 341 342 343
    }


    /**
     * Flush all of the Introspector's internal caches.  This method is
     * not normally required.  It is normally only needed by advanced
     * tools that update existing "Class" objects in-place and need
     * to make the Introspector re-analyze existing Class objects.
     */

    public static void flushCaches() {
344 345
        synchronized (declaredMethodCache) {
            ThreadGroupContext.getContext().clearBeanInfoCache();
346
            declaredMethodCache.clear();
347
        }
D
duke 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
    }

    /**
     * Flush the Introspector's internal cached information for a given class.
     * This method is not normally required.  It is normally only needed
     * by advanced tools that update existing "Class" objects in-place
     * and need to make the Introspector re-analyze an existing Class object.
     *
     * Note that only the direct state associated with the target Class
     * object is flushed.  We do not flush state for other Class objects
     * with the same name, nor do we flush state for any related Class
     * objects (such as subclasses), even though their state may include
     * information indirectly obtained from the target Class object.
     *
     * @param clz  Class object to be flushed.
     * @throws NullPointerException If the Class object is null.
     */
    public static void flushFromCaches(Class<?> clz) {
        if (clz == null) {
            throw new NullPointerException();
        }
369 370
        synchronized (declaredMethodCache) {
            ThreadGroupContext.getContext().removeBeanInfo(clz);
371
            declaredMethodCache.put(clz, null);
372
        }
D
duke 已提交
373 374 375 376 377 378
    }

    //======================================================================
    //                  Private implementation methods
    //======================================================================

379
    private Introspector(Class<?> beanClass, Class<?> stopClass, int flags)
D
duke 已提交
380 381 382 383 384 385
                                            throws IntrospectionException {
        this.beanClass = beanClass;

        // Check stopClass is a superClass of startClass.
        if (stopClass != null) {
            boolean isSuper = false;
386
            for (Class<?> c = beanClass.getSuperclass(); c != null; c = c.getSuperclass()) {
D
duke 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400
                if (c == stopClass) {
                    isSuper = true;
                }
            }
            if (!isSuper) {
                throw new IntrospectionException(stopClass.getName() + " not superclass of " +
                                        beanClass.getName());
            }
        }

        if (flags == USE_ALL_BEANINFO) {
            explicitBeanInfo = findExplicitBeanInfo(beanClass);
        }

401
        Class<?> superClass = beanClass.getSuperclass();
D
duke 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        if (superClass != stopClass) {
            int newFlags = flags;
            if (newFlags == IGNORE_IMMEDIATE_BEANINFO) {
                newFlags = USE_ALL_BEANINFO;
            }
            superBeanInfo = getBeanInfo(superClass, stopClass, newFlags);
        }
        if (explicitBeanInfo != null) {
            additionalBeanInfo = explicitBeanInfo.getAdditionalBeanInfo();
        }
        if (additionalBeanInfo == null) {
            additionalBeanInfo = new BeanInfo[0];
        }
    }

    /**
     * Constructs a GenericBeanInfo class from the state of the Introspector
     */
    private BeanInfo getBeanInfo() throws IntrospectionException {

        // the evaluation order here is import, as we evaluate the
        // event sets and locate PropertyChangeListeners before we
        // look for properties.
        BeanDescriptor bd = getTargetBeanDescriptor();
        MethodDescriptor mds[] = getTargetMethodInfo();
        EventSetDescriptor esds[] = getTargetEventInfo();
        PropertyDescriptor pds[] = getTargetPropertyInfo();

        int defaultEvent = getTargetDefaultEventIndex();
        int defaultProperty = getTargetDefaultPropertyIndex();

        return new GenericBeanInfo(bd, esds, defaultEvent, pds,
                        defaultProperty, mds, explicitBeanInfo);

    }

    /**
     * Looks for an explicit BeanInfo class that corresponds to the Class.
     * First it looks in the existing package that the Class is defined in,
     * then it checks to see if the class is its own BeanInfo. Finally,
     * the BeanInfo search path is prepended to the class and searched.
     *
444
     * @param beanClass  the class type of the bean
D
duke 已提交
445 446
     * @return Instance of an explicit BeanInfo class or null if one isn't found.
     */
447
    private static BeanInfo findExplicitBeanInfo(Class<?> beanClass) {
448
        return ThreadGroupContext.getContext().getBeanInfoFinder().find(beanClass);
D
duke 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    }

    /**
     * @return An array of PropertyDescriptors describing the editable
     * properties supported by the target bean.
     */

    private PropertyDescriptor[] getTargetPropertyInfo() {

        // Check if the bean has its own BeanInfo that will provide
        // explicit information.
        PropertyDescriptor[] explicitProperties = null;
        if (explicitBeanInfo != null) {
            explicitProperties = getPropertyDescriptors(this.explicitBeanInfo);
        }

        if (explicitProperties == null && superBeanInfo != null) {
            // We have no explicit BeanInfo properties.  Check with our parent.
            addPropertyDescriptors(getPropertyDescriptors(this.superBeanInfo));
        }

        for (int i = 0; i < additionalBeanInfo.length; i++) {
            addPropertyDescriptors(additionalBeanInfo[i].getPropertyDescriptors());
        }

        if (explicitProperties != null) {
            // Add the explicit BeanInfo data to our results.
            addPropertyDescriptors(explicitProperties);

        } else {

            // Apply some reflection to the current class.

            // First get an array of all the public methods at this level
            Method methodList[] = getPublicDeclaredMethods(beanClass);

            // Now analyze each method.
            for (int i = 0; i < methodList.length; i++) {
                Method method = methodList[i];
488
                if (method == null) {
D
duke 已提交
489 490 491 492 493 494 495 496
                    continue;
                }
                // skip static methods.
                int mods = method.getModifiers();
                if (Modifier.isStatic(mods)) {
                    continue;
                }
                String name = method.getName();
497 498
                Class<?>[] argTypes = method.getParameterTypes();
                Class<?> resultType = method.getReturnType();
D
duke 已提交
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
                int argCount = argTypes.length;
                PropertyDescriptor pd = null;

                if (name.length() <= 3 && !name.startsWith(IS_PREFIX)) {
                    // Optimization. Don't bother with invalid propertyNames.
                    continue;
                }

                try {

                    if (argCount == 0) {
                        if (name.startsWith(GET_PREFIX)) {
                            // Simple getter
                            pd = new PropertyDescriptor(this.beanClass, name.substring(3), method, null);
                        } else if (resultType == boolean.class && name.startsWith(IS_PREFIX)) {
                            // Boolean getter
                            pd = new PropertyDescriptor(this.beanClass, name.substring(2), method, null);
                        }
                    } else if (argCount == 1) {
518
                        if (int.class.equals(argTypes[0]) && name.startsWith(GET_PREFIX)) {
D
duke 已提交
519
                            pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, method, null);
520
                        } else if (void.class.equals(resultType) && name.startsWith(SET_PREFIX)) {
D
duke 已提交
521 522 523 524 525 526 527
                            // Simple setter
                            pd = new PropertyDescriptor(this.beanClass, name.substring(3), null, method);
                            if (throwsException(method, PropertyVetoException.class)) {
                                pd.setConstrained(true);
                            }
                        }
                    } else if (argCount == 2) {
528
                            if (void.class.equals(resultType) && int.class.equals(argTypes[0]) && name.startsWith(SET_PREFIX)) {
D
duke 已提交
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
                            pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, null, method);
                            if (throwsException(method, PropertyVetoException.class)) {
                                pd.setConstrained(true);
                            }
                        }
                    }
                } catch (IntrospectionException ex) {
                    // This happens if a PropertyDescriptor or IndexedPropertyDescriptor
                    // constructor fins that the method violates details of the deisgn
                    // pattern, e.g. by having an empty name, or a getter returning
                    // void , or whatever.
                    pd = null;
                }

                if (pd != null) {
                    // If this class or one of its base classes is a PropertyChange
                    // source, then we assume that any properties we discover are "bound".
                    if (propertyChangeSource) {
                        pd.setBound(true);
                    }
                    addPropertyDescriptor(pd);
                }
            }
        }
        processPropertyDescriptors();

        // Allocate and populate the result array.
556 557
        PropertyDescriptor result[] =
                properties.values().toArray(new PropertyDescriptor[properties.size()]);
D
duke 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570

        // Set the default index.
        if (defaultPropertyName != null) {
            for (int i = 0; i < result.length; i++) {
                if (defaultPropertyName.equals(result[i].getName())) {
                    defaultPropertyIndex = i;
                }
            }
        }

        return result;
    }

571
    private HashMap<String, List<PropertyDescriptor>> pdStore = new HashMap<>();
D
duke 已提交
572 573 574 575 576 577

    /**
     * Adds the property descriptor to the list store.
     */
    private void addPropertyDescriptor(PropertyDescriptor pd) {
        String propName = pd.getName();
578
        List<PropertyDescriptor> list = pdStore.get(propName);
D
duke 已提交
579
        if (list == null) {
580
            list = new ArrayList<>();
D
duke 已提交
581 582 583 584 585 586
            pdStore.put(propName, list);
        }
        if (this.beanClass != pd.getClass0()) {
            // replace existing property descriptor
            // only if we have types to resolve
            // in the context of this.beanClass
587 588 589 590 591 592 593 594 595 596 597 598 599 600
            Method read = pd.getReadMethod();
            Method write = pd.getWriteMethod();
            boolean cls = true;
            if (read != null) cls = cls && read.getGenericReturnType() instanceof Class;
            if (write != null) cls = cls && write.getGenericParameterTypes()[0] instanceof Class;
            if (pd instanceof IndexedPropertyDescriptor) {
                IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
                Method readI = ipd.getIndexedReadMethod();
                Method writeI = ipd.getIndexedWriteMethod();
                if (readI != null) cls = cls && readI.getGenericReturnType() instanceof Class;
                if (writeI != null) cls = cls && writeI.getGenericParameterTypes()[1] instanceof Class;
                if (!cls) {
                    pd = new IndexedPropertyDescriptor(ipd);
                    pd.updateGenericsFor(this.beanClass);
D
duke 已提交
601
                }
602 603 604 605
            }
            else if (!cls) {
                pd = new PropertyDescriptor(pd);
                pd.updateGenericsFor(this.beanClass);
D
duke 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
            }
        }
        list.add(pd);
    }

    private void addPropertyDescriptors(PropertyDescriptor[] descriptors) {
        if (descriptors != null) {
            for (PropertyDescriptor descriptor : descriptors) {
                addPropertyDescriptor(descriptor);
            }
        }
    }

    private PropertyDescriptor[] getPropertyDescriptors(BeanInfo info) {
        PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
        int index = info.getDefaultPropertyIndex();
        if ((0 <= index) && (index < descriptors.length)) {
            this.defaultPropertyName = descriptors[index].getName();
        }
        return descriptors;
    }

    /**
     * Populates the property descriptor table by merging the
     * lists of Property descriptors.
     */
    private void processPropertyDescriptors() {
        if (properties == null) {
634
            properties = new TreeMap<>();
D
duke 已提交
635 636
        }

637
        List<PropertyDescriptor> list;
D
duke 已提交
638 639 640 641

        PropertyDescriptor pd, gpd, spd;
        IndexedPropertyDescriptor ipd, igpd, ispd;

642
        Iterator<List<PropertyDescriptor>> it = pdStore.values().iterator();
D
duke 已提交
643 644 645 646
        while (it.hasNext()) {
            pd = null; gpd = null; spd = null;
            ipd = null; igpd = null; ispd = null;

647
            list = it.next();
D
duke 已提交
648 649 650 651

            // First pass. Find the latest getter method. Merge properties
            // of previous getter methods.
            for (int i = 0; i < list.size(); i++) {
652
                pd = list.get(i);
D
duke 已提交
653 654 655 656 657 658 659 660 661 662 663
                if (pd instanceof IndexedPropertyDescriptor) {
                    ipd = (IndexedPropertyDescriptor)pd;
                    if (ipd.getIndexedReadMethod() != null) {
                        if (igpd != null) {
                            igpd = new IndexedPropertyDescriptor(igpd, ipd);
                        } else {
                            igpd = ipd;
                        }
                    }
                } else {
                    if (pd.getReadMethod() != null) {
664
                        String pdName = pd.getReadMethod().getName();
D
duke 已提交
665 666 667
                        if (gpd != null) {
                            // Don't replace the existing read
                            // method if it starts with "is"
668 669
                            String gpdName = gpd.getReadMethod().getName();
                            if (gpdName.equals(pdName) || !gpdName.startsWith(IS_PREFIX)) {
D
duke 已提交
670 671 672 673 674 675 676 677 678 679 680 681
                                gpd = new PropertyDescriptor(gpd, pd);
                            }
                        } else {
                            gpd = pd;
                        }
                    }
                }
            }

            // Second pass. Find the latest setter method which
            // has the same type as the getter method.
            for (int i = 0; i < list.size(); i++) {
682
                pd = list.get(i);
D
duke 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
                if (pd instanceof IndexedPropertyDescriptor) {
                    ipd = (IndexedPropertyDescriptor)pd;
                    if (ipd.getIndexedWriteMethod() != null) {
                        if (igpd != null) {
                            if (igpd.getIndexedPropertyType()
                                == ipd.getIndexedPropertyType()) {
                                if (ispd != null) {
                                    ispd = new IndexedPropertyDescriptor(ispd, ipd);
                                } else {
                                    ispd = ipd;
                                }
                            }
                        } else {
                            if (ispd != null) {
                                ispd = new IndexedPropertyDescriptor(ispd, ipd);
                            } else {
                                ispd = ipd;
                            }
                        }
                    }
                } else {
                    if (pd.getWriteMethod() != null) {
                        if (gpd != null) {
                            if (gpd.getPropertyType() == pd.getPropertyType()) {
                                if (spd != null) {
                                    spd = new PropertyDescriptor(spd, pd);
                                } else {
                                    spd = pd;
                                }
                            }
                        } else {
                            if (spd != null) {
                                spd = new PropertyDescriptor(spd, pd);
                            } else {
                                spd = pd;
                            }
                        }
                    }
                }
            }

            // At this stage we should have either PDs or IPDs for the
            // representative getters and setters. The order at which the
            // property descriptors are determined represent the
            // precedence of the property ordering.
            pd = null; ipd = null;

            if (igpd != null && ispd != null) {
                // Complete indexed properties set
                // Merge any classic property descriptors
                if (gpd != null) {
                    PropertyDescriptor tpd = mergePropertyDescriptor(igpd, gpd);
                    if (tpd instanceof IndexedPropertyDescriptor) {
                        igpd = (IndexedPropertyDescriptor)tpd;
                    }
                }
                if (spd != null) {
                    PropertyDescriptor tpd = mergePropertyDescriptor(ispd, spd);
                    if (tpd instanceof IndexedPropertyDescriptor) {
                        ispd = (IndexedPropertyDescriptor)tpd;
                    }
                }
                if (igpd == ispd) {
                    pd = igpd;
                } else {
                    pd = mergePropertyDescriptor(igpd, ispd);
                }
            } else if (gpd != null && spd != null) {
                // Complete simple properties set
                if (gpd == spd) {
                    pd = gpd;
                } else {
                    pd = mergePropertyDescriptor(gpd, spd);
                }
            } else if (ispd != null) {
                // indexed setter
                pd = ispd;
                // Merge any classic property descriptors
                if (spd != null) {
                    pd = mergePropertyDescriptor(ispd, spd);
                }
                if (gpd != null) {
                    pd = mergePropertyDescriptor(ispd, gpd);
                }
            } else if (igpd != null) {
                // indexed getter
                pd = igpd;
                // Merge any classic property descriptors
                if (gpd != null) {
                    pd = mergePropertyDescriptor(igpd, gpd);
                }
                if (spd != null) {
                    pd = mergePropertyDescriptor(igpd, spd);
                }
            } else if (spd != null) {
                // simple setter
                pd = spd;
            } else if (gpd != null) {
                // simple getter
                pd = gpd;
            }

            // Very special case to ensure that an IndexedPropertyDescriptor
            // doesn't contain less information than the enclosed
            // PropertyDescriptor. If it does, then recreate as a
            // PropertyDescriptor. See 4168833
            if (pd instanceof IndexedPropertyDescriptor) {
                ipd = (IndexedPropertyDescriptor)pd;
                if (ipd.getIndexedReadMethod() == null && ipd.getIndexedWriteMethod() == null) {
                    pd = new PropertyDescriptor(ipd);
                }
            }

            // Find the first property descriptor
            // which does not have getter and setter methods.
            // See regression bug 4984912.
            if ( (pd == null) && (list.size() > 0) ) {
800
                pd = list.get(0);
D
duke 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
            }

            if (pd != null) {
                properties.put(pd.getName(), pd);
            }
        }
    }

    /**
     * Adds the property descriptor to the indexedproperty descriptor only if the
     * types are the same.
     *
     * The most specific property descriptor will take precedence.
     */
    private PropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd,
                                                       PropertyDescriptor pd) {
        PropertyDescriptor result = null;

819 820
        Class<?> propType = pd.getPropertyType();
        Class<?> ipropType = ipd.getIndexedPropertyType();
D
duke 已提交
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840

        if (propType.isArray() && propType.getComponentType() == ipropType) {
            if (pd.getClass0().isAssignableFrom(ipd.getClass0())) {
                result = new IndexedPropertyDescriptor(pd, ipd);
            } else {
                result = new IndexedPropertyDescriptor(ipd, pd);
            }
        } else {
            // Cannot merge the pd because of type mismatch
            // Return the most specific pd
            if (pd.getClass0().isAssignableFrom(ipd.getClass0())) {
                result = ipd;
            } else {
                result = pd;
                // Try to add methods which may have been lost in the type change
                // See 4168833
                Method write = result.getWriteMethod();
                Method read = result.getReadMethod();

                if (read == null && write != null) {
841 842
                    read = findMethod(result.getClass0(),
                                      GET_PREFIX + NameGenerator.capitalize(result.getName()), 0);
D
duke 已提交
843 844 845 846 847 848 849 850 851
                    if (read != null) {
                        try {
                            result.setReadMethod(read);
                        } catch (IntrospectionException ex) {
                            // no consequences for failure.
                        }
                    }
                }
                if (write == null && read != null) {
852 853
                    write = findMethod(result.getClass0(),
                                       SET_PREFIX + NameGenerator.capitalize(result.getName()), 1,
854
                                       new Class<?>[] { FeatureDescriptor.getReturnType(result.getClass0(), read) });
D
duke 已提交
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
                    if (write != null) {
                        try {
                            result.setWriteMethod(write);
                        } catch (IntrospectionException ex) {
                            // no consequences for failure.
                        }
                    }
                }
            }
        }
        return result;
    }

    // Handle regular pd merge
    private PropertyDescriptor mergePropertyDescriptor(PropertyDescriptor pd1,
                                                       PropertyDescriptor pd2) {
        if (pd1.getClass0().isAssignableFrom(pd2.getClass0())) {
            return new PropertyDescriptor(pd1, pd2);
        } else {
            return new PropertyDescriptor(pd2, pd1);
        }
    }

    // Handle regular ipd merge
    private PropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd1,
                                                       IndexedPropertyDescriptor ipd2) {
        if (ipd1.getClass0().isAssignableFrom(ipd2.getClass0())) {
            return new IndexedPropertyDescriptor(ipd1, ipd2);
        } else {
            return new IndexedPropertyDescriptor(ipd2, ipd1);
        }
    }

    /**
     * @return An array of EventSetDescriptors describing the kinds of
     * events fired by the target bean.
     */
    private EventSetDescriptor[] getTargetEventInfo() throws IntrospectionException {
        if (events == null) {
894
            events = new HashMap<>();
D
duke 已提交
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
        }

        // Check if the bean has its own BeanInfo that will provide
        // explicit information.
        EventSetDescriptor[] explicitEvents = null;
        if (explicitBeanInfo != null) {
            explicitEvents = explicitBeanInfo.getEventSetDescriptors();
            int ix = explicitBeanInfo.getDefaultEventIndex();
            if (ix >= 0 && ix < explicitEvents.length) {
                defaultEventName = explicitEvents[ix].getName();
            }
        }

        if (explicitEvents == null && superBeanInfo != null) {
            // We have no explicit BeanInfo events.  Check with our parent.
            EventSetDescriptor supers[] = superBeanInfo.getEventSetDescriptors();
            for (int i = 0 ; i < supers.length; i++) {
                addEvent(supers[i]);
            }
            int ix = superBeanInfo.getDefaultEventIndex();
            if (ix >= 0 && ix < supers.length) {
                defaultEventName = supers[ix].getName();
            }
        }

        for (int i = 0; i < additionalBeanInfo.length; i++) {
            EventSetDescriptor additional[] = additionalBeanInfo[i].getEventSetDescriptors();
            if (additional != null) {
                for (int j = 0 ; j < additional.length; j++) {
                    addEvent(additional[j]);
                }
            }
        }

        if (explicitEvents != null) {
            // Add the explicit explicitBeanInfo data to our results.
            for (int i = 0 ; i < explicitEvents.length; i++) {
                addEvent(explicitEvents[i]);
            }

        } else {

            // Apply some reflection to the current class.

            // Get an array of all the public beans methods at this level
            Method methodList[] = getPublicDeclaredMethods(beanClass);

            // Find all suitable "add", "remove" and "get" Listener methods
            // The name of the listener type is the key for these hashtables
            // i.e, ActionListener
945 946 947
            Map<String, Method> adds = null;
            Map<String, Method> removes = null;
            Map<String, Method> gets = null;
D
duke 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965

            for (int i = 0; i < methodList.length; i++) {
                Method method = methodList[i];
                if (method == null) {
                    continue;
                }
                // skip static methods.
                int mods = method.getModifiers();
                if (Modifier.isStatic(mods)) {
                    continue;
                }
                String name = method.getName();
                // Optimization avoid getParameterTypes
                if (!name.startsWith(ADD_PREFIX) && !name.startsWith(REMOVE_PREFIX)
                    && !name.startsWith(GET_PREFIX)) {
                    continue;
                }

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
                if (name.startsWith(ADD_PREFIX)) {
                    Class<?> returnType = method.getReturnType();
                    if (returnType == void.class) {
                        Type[] parameterTypes = method.getGenericParameterTypes();
                        if (parameterTypes.length == 1) {
                            Class<?> type = TypeResolver.erase(TypeResolver.resolveInClass(beanClass, parameterTypes[0]));
                            if (Introspector.isSubclass(type, eventListenerType)) {
                                String listenerName = name.substring(3);
                                if (listenerName.length() > 0 &&
                                    type.getName().endsWith(listenerName)) {
                                    if (adds == null) {
                                        adds = new HashMap<>();
                                    }
                                    adds.put(listenerName, method);
                                }
                            }
D
duke 已提交
982 983 984
                        }
                    }
                }
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
                else if (name.startsWith(REMOVE_PREFIX)) {
                    Class<?> returnType = method.getReturnType();
                    if (returnType == void.class) {
                        Type[] parameterTypes = method.getGenericParameterTypes();
                        if (parameterTypes.length == 1) {
                            Class<?> type = TypeResolver.erase(TypeResolver.resolveInClass(beanClass, parameterTypes[0]));
                            if (Introspector.isSubclass(type, eventListenerType)) {
                                String listenerName = name.substring(6);
                                if (listenerName.length() > 0 &&
                                    type.getName().endsWith(listenerName)) {
                                    if (removes == null) {
                                        removes = new HashMap<>();
                                    }
                                    removes.put(listenerName, method);
                                }
                            }
D
duke 已提交
1001 1002 1003
                        }
                    }
                }
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
                else if (name.startsWith(GET_PREFIX)) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    if (parameterTypes.length == 0) {
                        Class<?> returnType = FeatureDescriptor.getReturnType(beanClass, method);
                        if (returnType.isArray()) {
                            Class<?> type = returnType.getComponentType();
                            if (Introspector.isSubclass(type, eventListenerType)) {
                                String listenerName  = name.substring(3, name.length() - 1);
                                if (listenerName.length() > 0 &&
                                    type.getName().endsWith(listenerName)) {
                                    if (gets == null) {
                                        gets = new HashMap<>();
                                    }
                                    gets.put(listenerName, method);
                                }
                            }
D
duke 已提交
1020 1021 1022 1023 1024 1025 1026 1027
                        }
                    }
                }
            }

            if (adds != null && removes != null) {
                // Now look for matching addFooListener+removeFooListener pairs.
                // Bonus if there is a matching getFooListeners method as well.
1028
                Iterator<String> keys = adds.keySet().iterator();
D
duke 已提交
1029
                while (keys.hasNext()) {
1030
                    String listenerName = keys.next();
D
duke 已提交
1031 1032 1033 1034 1035 1036
                    // Skip any "add" which doesn't have a matching "remove" or
                    // a listener name that doesn't end with Listener
                    if (removes.get(listenerName) == null || !listenerName.endsWith("Listener")) {
                        continue;
                    }
                    String eventName = decapitalize(listenerName.substring(0, listenerName.length()-8));
1037 1038
                    Method addMethod = adds.get(listenerName);
                    Method removeMethod = removes.get(listenerName);
D
duke 已提交
1039 1040
                    Method getMethod = null;
                    if (gets != null) {
1041
                        getMethod = gets.get(listenerName);
D
duke 已提交
1042
                    }
1043
                    Class<?> argType = FeatureDescriptor.getParameterTypes(beanClass, addMethod)[0];
D
duke 已提交
1044 1045 1046

                    // generate a list of Method objects for each of the target methods:
                    Method allMethods[] = getPublicDeclaredMethods(argType);
1047
                    List<Method> validMethods = new ArrayList<>(allMethods.length);
D
duke 已提交
1048 1049 1050 1051 1052 1053 1054 1055 1056
                    for (int i = 0; i < allMethods.length; i++) {
                        if (allMethods[i] == null) {
                            continue;
                        }

                        if (isEventHandler(allMethods[i])) {
                            validMethods.add(allMethods[i]);
                        }
                    }
1057
                    Method[] methods = validMethods.toArray(new Method[validMethods.size()]);
D
duke 已提交
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

                    EventSetDescriptor esd = new EventSetDescriptor(eventName, argType,
                                                                    methods, addMethod,
                                                                    removeMethod,
                                                                    getMethod);

                    // If the adder method throws the TooManyListenersException then it
                    // is a Unicast event source.
                    if (throwsException(addMethod,
                                        java.util.TooManyListenersException.class)) {
                        esd.setUnicast(true);
                    }
                    addEvent(esd);
                }
            } // if (adds != null ...
        }
        EventSetDescriptor[] result;
        if (events.size() == 0) {
            result = EMPTY_EVENTSETDESCRIPTORS;
        } else {
            // Allocate and populate the result array.
            result = new EventSetDescriptor[events.size()];
1080
            result = events.values().toArray(result);
D
duke 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098

            // Set the default index.
            if (defaultEventName != null) {
                for (int i = 0; i < result.length; i++) {
                    if (defaultEventName.equals(result[i].getName())) {
                        defaultEventIndex = i;
                    }
                }
            }
        }
        return result;
    }

    private void addEvent(EventSetDescriptor esd) {
        String key = esd.getName();
        if (esd.getName().equals("propertyChange")) {
            propertyChangeSource = true;
        }
1099
        EventSetDescriptor old = events.get(key);
D
duke 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
        if (old == null) {
            events.put(key, esd);
            return;
        }
        EventSetDescriptor composite = new EventSetDescriptor(old, esd);
        events.put(key, composite);
    }

    /**
     * @return An array of MethodDescriptors describing the private
     * methods supported by the target bean.
     */
    private MethodDescriptor[] getTargetMethodInfo() {
        if (methods == null) {
1114
            methods = new HashMap<>(100);
D
duke 已提交
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
        }

        // Check if the bean has its own BeanInfo that will provide
        // explicit information.
        MethodDescriptor[] explicitMethods = null;
        if (explicitBeanInfo != null) {
            explicitMethods = explicitBeanInfo.getMethodDescriptors();
        }

        if (explicitMethods == null && superBeanInfo != null) {
            // We have no explicit BeanInfo methods.  Check with our parent.
            MethodDescriptor supers[] = superBeanInfo.getMethodDescriptors();
            for (int i = 0 ; i < supers.length; i++) {
                addMethod(supers[i]);
            }
        }

        for (int i = 0; i < additionalBeanInfo.length; i++) {
            MethodDescriptor additional[] = additionalBeanInfo[i].getMethodDescriptors();
            if (additional != null) {
                for (int j = 0 ; j < additional.length; j++) {
                    addMethod(additional[j]);
                }
            }
        }

        if (explicitMethods != null) {
            // Add the explicit explicitBeanInfo data to our results.
            for (int i = 0 ; i < explicitMethods.length; i++) {
                addMethod(explicitMethods[i]);
            }

        } else {

            // Apply some reflection to the current class.

            // First get an array of all the beans methods at this level
            Method methodList[] = getPublicDeclaredMethods(beanClass);

            // Now analyze each method.
            for (int i = 0; i < methodList.length; i++) {
                Method method = methodList[i];
                if (method == null) {
                    continue;
                }
                MethodDescriptor md = new MethodDescriptor(method);
                addMethod(md);
            }
        }

        // Allocate and populate the result array.
        MethodDescriptor result[] = new MethodDescriptor[methods.size()];
1167
        result = methods.values().toArray(result);
D
duke 已提交
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177

        return result;
    }

    private void addMethod(MethodDescriptor md) {
        // We have to be careful here to distinguish method by both name
        // and argument lists.
        // This method gets called a *lot, so we try to be efficient.
        String name = md.getName();

1178
        MethodDescriptor old = methods.get(name);
D
duke 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
        if (old == null) {
            // This is the common case.
            methods.put(name, md);
            return;
        }

        // We have a collision on method names.  This is rare.

        // Check if old and md have the same type.
        String[] p1 = md.getParamNames();
        String[] p2 = old.getParamNames();

        boolean match = false;
        if (p1.length == p2.length) {
            match = true;
            for (int i = 0; i < p1.length; i++) {
                if (p1[i] != p2[i]) {
                    match = false;
                    break;
                }
            }
        }
        if (match) {
            MethodDescriptor composite = new MethodDescriptor(old, md);
            methods.put(name, composite);
            return;
        }

        // We have a collision on method names with different type signatures.
        // This is very rare.

        String longKey = makeQualifiedMethodName(name, p1);
1211
        old = methods.get(longKey);
D
duke 已提交
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
        if (old == null) {
            methods.put(longKey, md);
            return;
        }
        MethodDescriptor composite = new MethodDescriptor(old, md);
        methods.put(longKey, composite);
    }

    /**
     * Creates a key for a method in a method cache.
     */
    private static String makeQualifiedMethodName(String name, String[] params) {
        StringBuffer sb = new StringBuffer(name);
        sb.append('=');
        for (int i = 0; i < params.length; i++) {
            sb.append(':');
            sb.append(params[i]);
        }
        return sb.toString();
    }

    private int getTargetDefaultEventIndex() {
        return defaultEventIndex;
    }

    private int getTargetDefaultPropertyIndex() {
        return defaultPropertyIndex;
    }

    private BeanDescriptor getTargetBeanDescriptor() {
        // Use explicit info, if available,
        if (explicitBeanInfo != null) {
            BeanDescriptor bd = explicitBeanInfo.getBeanDescriptor();
            if (bd != null) {
                return (bd);
            }
        }
        // OK, fabricate a default BeanDescriptor.
1250 1251 1252 1253 1254 1255 1256 1257
        return new BeanDescriptor(this.beanClass, findCustomizerClass(this.beanClass));
    }

    private static Class<?> findCustomizerClass(Class<?> type) {
        String name = type.getName() + "Customizer";
        try {
            type = ClassFinder.findClass(name, type.getClassLoader());
            // Each customizer should inherit java.awt.Component and implement java.beans.Customizer
1258
            // according to the section 9.3 of JavaBeans&trade; specification
1259 1260 1261 1262 1263 1264 1265 1266
            if (Component.class.isAssignableFrom(type) && Customizer.class.isAssignableFrom(type)) {
                return type;
            }
        }
        catch (Exception exception) {
            // ignore any exceptions
        }
        return null;
D
duke 已提交
1267 1268 1269 1270 1271
    }

    private boolean isEventHandler(Method m) {
        // We assume that a method is an event handler if it has a single
        // argument, whose type inherit from java.util.Event.
1272
        Type argTypes[] = m.getGenericParameterTypes();
D
duke 已提交
1273 1274 1275
        if (argTypes.length != 1) {
            return false;
        }
1276
        return isSubclass(TypeResolver.erase(TypeResolver.resolveInClass(beanClass, argTypes[0])), EventObject.class);
D
duke 已提交
1277 1278 1279 1280 1281
    }

    /*
     * Internal method to return *public* methods within a class.
     */
1282
    private static Method[] getPublicDeclaredMethods(Class<?> clz) {
D
duke 已提交
1283 1284 1285 1286 1287
        // Looking up Class.getDeclaredMethods is relatively expensive,
        // so we cache the results.
        if (!ReflectUtil.isPackageAccessible(clz)) {
            return new Method[0];
        }
1288
        synchronized (declaredMethodCache) {
1289 1290 1291 1292 1293 1294
            Method[] result = declaredMethodCache.get(clz);
            if (result == null) {
                result = clz.getMethods();
                for (int i = 0; i < result.length; i++) {
                    Method method = result[i];
                    if (!method.getDeclaringClass().equals(clz)) {
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
                        result[i] = null; // ignore methods declared elsewhere
                    }
                    else {
                        try {
                            method = MethodFinder.findAccessibleMethod(method);
                            Class<?> type = method.getDeclaringClass();
                            result[i] = type.equals(clz) || type.isInterface()
                                    ? method
                                    : null; // ignore methods from superclasses
                        }
                        catch (NoSuchMethodException exception) {
                            // commented out because of 6976577
                            // result[i] = null; // ignore inaccessible methods
                        }
1309
                    }
D
duke 已提交
1310
                }
1311
                declaredMethodCache.put(clz, result);
D
duke 已提交
1312
            }
1313
            return result;
D
duke 已提交
1314 1315 1316 1317 1318 1319 1320
        }
    }

    //======================================================================
    // Package private support methods.
    //======================================================================

1321 1322 1323 1324
    /**
     * Internal support for finding a target methodName with a given
     * parameter list on a given class.
     */
1325
    private static Method internalFindMethod(Class<?> start, String methodName,
1326 1327 1328 1329 1330 1331
                                                 int argCount, Class args[]) {
        // For overriden methods we need to find the most derived version.
        // So we start with the given class and walk up the superclass chain.

        Method method = null;

1332
        for (Class<?> cl = start; cl != null; cl = cl.getSuperclass()) {
1333 1334 1335 1336 1337
            Method methods[] = getPublicDeclaredMethods(cl);
            for (int i = 0; i < methods.length; i++) {
                method = methods[i];
                if (method == null) {
                    continue;
D
duke 已提交
1338
                }
1339 1340

                // make sure method signature matches.
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
                if (method.getName().equals(methodName)) {
                    Type[] params = method.getGenericParameterTypes();
                    if (params.length == argCount) {
                        if (args != null) {
                            boolean different = false;
                            if (argCount > 0) {
                                for (int j = 0; j < argCount; j++) {
                                    if (TypeResolver.erase(TypeResolver.resolveInClass(start, params[j])) != args[j]) {
                                        different = true;
                                        continue;
                                    }
                                }
                                if (different) {
1354 1355 1356 1357
                                    continue;
                                }
                            }
                        }
1358
                        return method;
1359
                    }
D
duke 已提交
1360 1361 1362
                }
            }
        }
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        method = null;

        // Now check any inherited interfaces.  This is necessary both when
        // the argument class is itself an interface, and when the argument
        // class is an abstract class.
        Class ifcs[] = start.getInterfaces();
        for (int i = 0 ; i < ifcs.length; i++) {
            // Note: The original implementation had both methods calling
            // the 3 arg method. This is preserved but perhaps it should
            // pass the args array instead of null.
            method = internalFindMethod(ifcs[i], methodName, argCount, null);
            if (method != null) {
                break;
            }
        }
        return method;
D
duke 已提交
1379 1380
    }

1381 1382 1383
    /**
     * Find a target methodName on a given class.
     */
1384
    static Method findMethod(Class<?> cls, String methodName, int argCount) {
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
        return findMethod(cls, methodName, argCount, null);
    }

    /**
     * Find a target methodName with specific parameter list on a given class.
     * <p>
     * Used in the contructors of the EventSetDescriptor,
     * PropertyDescriptor and the IndexedPropertyDescriptor.
     * <p>
     * @param cls The Class object on which to retrieve the method.
     * @param methodName Name of the method.
     * @param argCount Number of arguments for the desired method.
     * @param args Array of argument types for the method.
     * @return the method or null if not found
     */
1400
    static Method findMethod(Class<?> cls, String methodName, int argCount,
1401 1402
                             Class args[]) {
        if (methodName == null) {
D
duke 已提交
1403 1404
            return null;
        }
1405
        return internalFindMethod(cls, methodName, argCount, args);
D
duke 已提交
1406 1407 1408 1409 1410 1411 1412 1413
    }

    /**
     * Return true if class a is either equivalent to class b, or
     * if class a is a subclass of class b, i.e. if a either "extends"
     * or "implements" b.
     * Note tht either or both "Class" objects may represent interfaces.
     */
1414
    static  boolean isSubclass(Class<?> a, Class<?> b) {
D
duke 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423
        // We rely on the fact that for any given java class or
        // primtitive type there is a unqiue Class object, so
        // we can use object equivalence in the comparisons.
        if (a == b) {
            return true;
        }
        if (a == null || b == null) {
            return false;
        }
1424
        for (Class<?> x = a; x != null; x = x.getSuperclass()) {
D
duke 已提交
1425 1426 1427 1428
            if (x == b) {
                return true;
            }
            if (b.isInterface()) {
1429
                Class<?>[] interfaces = x.getInterfaces();
D
duke 已提交
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
                for (int i = 0; i < interfaces.length; i++) {
                    if (isSubclass(interfaces[i], b)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * Return true iff the given method throws the given exception.
     */
1443
    private boolean throwsException(Method method, Class<?> exception) {
D
duke 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
        Class exs[] = method.getExceptionTypes();
        for (int i = 0; i < exs.length; i++) {
            if (exs[i] == exception) {
                return true;
            }
        }
        return false;
    }

    /**
     * Try to create an instance of a named class.
     * First try the classloader of "sibling", then try the system
     * classloader then the class loader of the current Thread.
     */
1458
    static Object instantiate(Class<?> sibling, String className)
D
duke 已提交
1459 1460 1461 1462
                 throws InstantiationException, IllegalAccessException,
                                                ClassNotFoundException {
        // First check with sibling's classloader (if any).
        ClassLoader cl = sibling.getClassLoader();
1463
        Class<?> cls = ClassFinder.findClass(className, cl);
D
duke 已提交
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
        return cls.newInstance();
    }

} // end class Introspector

//===========================================================================

/**
 * Package private implementation support class for Introspector's
 * internal use.
 * <p>
 * Mostly this is used as a placeholder for the descriptors.
 */

class GenericBeanInfo extends SimpleBeanInfo {

    private BeanDescriptor beanDescriptor;
    private EventSetDescriptor[] events;
    private int defaultEvent;
    private PropertyDescriptor[] properties;
    private int defaultProperty;
    private MethodDescriptor[] methods;
1486
    private Reference<BeanInfo> targetBeanInfoRef;
D
duke 已提交
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497

    public GenericBeanInfo(BeanDescriptor beanDescriptor,
                EventSetDescriptor[] events, int defaultEvent,
                PropertyDescriptor[] properties, int defaultProperty,
                MethodDescriptor[] methods, BeanInfo targetBeanInfo) {
        this.beanDescriptor = beanDescriptor;
        this.events = events;
        this.defaultEvent = defaultEvent;
        this.properties = properties;
        this.defaultProperty = defaultProperty;
        this.methods = methods;
1498 1499 1500
        this.targetBeanInfoRef = (targetBeanInfo != null)
                ? new SoftReference<>(targetBeanInfo)
                : null;
D
duke 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
    }

    /**
     * Package-private dup constructor
     * This must isolate the new object from any changes to the old object.
     */
    GenericBeanInfo(GenericBeanInfo old) {

        beanDescriptor = new BeanDescriptor(old.beanDescriptor);
        if (old.events != null) {
            int len = old.events.length;
            events = new EventSetDescriptor[len];
            for (int i = 0; i < len; i++) {
                events[i] = new EventSetDescriptor(old.events[i]);
            }
        }
        defaultEvent = old.defaultEvent;
        if (old.properties != null) {
            int len = old.properties.length;
            properties = new PropertyDescriptor[len];
            for (int i = 0; i < len; i++) {
                PropertyDescriptor oldp = old.properties[i];
                if (oldp instanceof IndexedPropertyDescriptor) {
                    properties[i] = new IndexedPropertyDescriptor(
                                        (IndexedPropertyDescriptor) oldp);
                } else {
                    properties[i] = new PropertyDescriptor(oldp);
                }
            }
        }
        defaultProperty = old.defaultProperty;
        if (old.methods != null) {
            int len = old.methods.length;
            methods = new MethodDescriptor[len];
            for (int i = 0; i < len; i++) {
                methods[i] = new MethodDescriptor(old.methods[i]);
            }
        }
1539
        this.targetBeanInfoRef = old.targetBeanInfoRef;
D
duke 已提交
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    }

    public PropertyDescriptor[] getPropertyDescriptors() {
        return properties;
    }

    public int getDefaultPropertyIndex() {
        return defaultProperty;
    }

    public EventSetDescriptor[] getEventSetDescriptors() {
        return events;
    }

    public int getDefaultEventIndex() {
        return defaultEvent;
    }

    public MethodDescriptor[] getMethodDescriptors() {
        return methods;
    }

    public BeanDescriptor getBeanDescriptor() {
        return beanDescriptor;
    }

    public java.awt.Image getIcon(int iconKind) {
1567
        BeanInfo targetBeanInfo = getTargetBeanInfo();
D
duke 已提交
1568 1569 1570 1571 1572
        if (targetBeanInfo != null) {
            return targetBeanInfo.getIcon(iconKind);
        }
        return super.getIcon(iconKind);
    }
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587

    private BeanInfo getTargetBeanInfo() {
        if (this.targetBeanInfoRef == null) {
            return null;
        }
        BeanInfo targetBeanInfo = this.targetBeanInfoRef.get();
        if (targetBeanInfo == null) {
            targetBeanInfo = ThreadGroupContext.getContext().getBeanInfoFinder()
                    .find(this.beanDescriptor.getBeanClass());
            if (targetBeanInfo != null) {
                this.targetBeanInfoRef = new SoftReference<>(targetBeanInfo);
            }
        }
        return targetBeanInfo;
    }
D
duke 已提交
1588
}