1 /*
   2  * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.beans;
  27 
  28 import com.sun.beans.TypeResolver;
  29 import com.sun.beans.WeakCache;
  30 import com.sun.beans.finder.ClassFinder;
  31 import com.sun.beans.finder.MethodFinder;
  32 
  33 import java.awt.Component;
  34 
  35 import java.lang.ref.Reference;
  36 import java.lang.ref.SoftReference;
  37 import java.lang.reflect.Method;
  38 import java.lang.reflect.Modifier;
  39 import java.lang.reflect.Type;
  40 
  41 import java.util.Map;
  42 import java.util.ArrayList;
  43 import java.util.HashMap;
  44 import java.util.Iterator;
  45 import java.util.EventListener;
  46 import java.util.EventObject;
  47 import java.util.List;
  48 import java.util.TreeMap;
  49 
  50 import sun.misc.JavaBeansIntrospectorAccess;
  51 import sun.misc.SharedSecrets;
  52 import sun.reflect.misc.ReflectUtil;
  53 
  54 /**
  55  * The Introspector class provides a standard way for tools to learn about
  56  * the properties, events, and methods supported by a target Java Bean.
  57  * <p>
  58  * For each of those three kinds of information, the Introspector will
  59  * separately analyze the bean's class and superclasses looking for
  60  * either explicit or implicit information and use that information to
  61  * build a BeanInfo object that comprehensively describes the target bean.
  62  * <p>
  63  * For each class "Foo", explicit information may be available if there exists
  64  * a corresponding "FooBeanInfo" class that provides a non-null value when
  65  * queried for the information.   We first look for the BeanInfo class by
  66  * taking the full package-qualified name of the target bean class and
  67  * appending "BeanInfo" to form a new class name.  If this fails, then
  68  * we take the final classname component of this name, and look for that
  69  * class in each of the packages specified in the BeanInfo package search
  70  * path.
  71  * <p>
  72  * Thus for a class such as "sun.xyz.OurButton" we would first look for a
  73  * BeanInfo class called "sun.xyz.OurButtonBeanInfo" and if that failed we'd
  74  * look in each package in the BeanInfo search path for an OurButtonBeanInfo
  75  * class.  With the default search path, this would mean looking for
  76  * "sun.beans.infos.OurButtonBeanInfo".
  77  * <p>
  78  * If a class provides explicit BeanInfo about itself then we add that to
  79  * the BeanInfo information we obtained from analyzing any derived classes,
  80  * but we regard the explicit information as being definitive for the current
  81  * class and its base classes, and do not proceed any further up the superclass
  82  * chain.
  83  * <p>
  84  * If we don't find explicit BeanInfo on a class, we use low-level
  85  * reflection to study the methods of the class and apply standard design
  86  * patterns to identify property accessors, event sources, or public
  87  * methods.  We then proceed to analyze the class's superclass and add
  88  * in the information from it (and possibly on up the superclass chain).
  89  * <p>
  90  * For more information about introspection and design patterns, please
  91  * consult the
  92  *  <a href="http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html">JavaBeans&trade; specification</a>.
  93  *
  94  * @since 1.1
  95  */
  96 
  97 public class Introspector {
  98 
  99     // Flags that can be used to control getBeanInfo:
 100     /**
 101      * Flag to indicate to use of all beaninfo.
 102      * @since 1.2
 103      */
 104     public final static int USE_ALL_BEANINFO           = 1;
 105     /**
 106      * Flag to indicate to ignore immediate beaninfo.
 107      * @since 1.2
 108      */
 109     public final static int IGNORE_IMMEDIATE_BEANINFO  = 2;
 110     /**
 111      * Flag to indicate to ignore all beaninfo.
 112      * @since 1.2
 113      */
 114     public final static int IGNORE_ALL_BEANINFO        = 3;
 115 
 116     // Static Caches to speed up introspection.
 117     private static final WeakCache<Class<?>, Method[]> declaredMethodCache = new WeakCache<>();
 118 
 119     private Class<?> beanClass;
 120     private BeanInfo explicitBeanInfo;
 121     private BeanInfo superBeanInfo;
 122     private BeanInfo additionalBeanInfo[];
 123 
 124     private boolean propertyChangeSource = false;
 125     private static Class<EventListener> eventListenerType = EventListener.class;
 126 
 127     // These should be removed.
 128     private String defaultEventName;
 129     private String defaultPropertyName;
 130     private int defaultEventIndex = -1;
 131     private int defaultPropertyIndex = -1;
 132 
 133     // Methods maps from Method names to MethodDescriptors
 134     private Map<String, MethodDescriptor> methods;
 135 
 136     // properties maps from String names to PropertyDescriptors
 137     private Map<String, PropertyDescriptor> properties;
 138 
 139     // events maps from String names to EventSetDescriptors
 140     private Map<String, EventSetDescriptor> events;
 141 
 142     private final static EventSetDescriptor[] EMPTY_EVENTSETDESCRIPTORS = new EventSetDescriptor[0];
 143 
 144     static final String ADD_PREFIX = "add";
 145     static final String REMOVE_PREFIX = "remove";
 146     static final String GET_PREFIX = "get";
 147     static final String SET_PREFIX = "set";
 148     static final String IS_PREFIX = "is";
 149 
 150     // register with SharedSecrets for JMX usage
 151     static {
 152         SharedSecrets.setJavaBeansIntrospectorAccess((clazz, property) -> {
 153             BeanInfo bi = Introspector.getBeanInfo(clazz);
 154             PropertyDescriptor[] pds = bi.getPropertyDescriptors();
 155             for (PropertyDescriptor pd: pds) {
 156                 if (pd.getName().equals(property)) {
 157                     return pd.getReadMethod();
 158                 }
 159             }
 160             return null;
 161         });
 162     }
 163 
 164     //======================================================================
 165     //                          Public methods
 166     //======================================================================
 167 
 168     /**
 169      * Introspect on a Java Bean and learn about all its properties, exposed
 170      * methods, and events.
 171      * <p>
 172      * If the BeanInfo class for a Java Bean has been previously Introspected
 173      * then the BeanInfo class is retrieved from the BeanInfo cache.
 174      *
 175      * @param beanClass  The bean class to be analyzed.
 176      * @return  A BeanInfo object describing the target bean.
 177      * @exception IntrospectionException if an exception occurs during
 178      *              introspection.
 179      * @see #flushCaches
 180      * @see #flushFromCaches
 181      */
 182     public static BeanInfo getBeanInfo(Class<?> beanClass)
 183         throws IntrospectionException
 184     {
 185         if (!ReflectUtil.isPackageAccessible(beanClass)) {
 186             return (new Introspector(beanClass, null, USE_ALL_BEANINFO)).getBeanInfo();
 187         }
 188         ThreadGroupContext context = ThreadGroupContext.getContext();
 189         BeanInfo beanInfo;
 190         synchronized (declaredMethodCache) {
 191             beanInfo = context.getBeanInfo(beanClass);
 192         }
 193         if (beanInfo == null) {
 194             beanInfo = new Introspector(beanClass, null, USE_ALL_BEANINFO).getBeanInfo();
 195             synchronized (declaredMethodCache) {
 196                 context.putBeanInfo(beanClass, beanInfo);
 197             }
 198         }
 199         return beanInfo;
 200     }
 201 
 202     /**
 203      * Introspect on a Java bean and learn about all its properties, exposed
 204      * methods, and events, subject to some control flags.
 205      * <p>
 206      * If the BeanInfo class for a Java Bean has been previously Introspected
 207      * based on the same arguments then the BeanInfo class is retrieved
 208      * from the BeanInfo cache.
 209      *
 210      * @param beanClass  The bean class to be analyzed.
 211      * @param flags  Flags to control the introspection.
 212      *     If flags == USE_ALL_BEANINFO then we use all of the BeanInfo
 213      *          classes we can discover.
 214      *     If flags == IGNORE_IMMEDIATE_BEANINFO then we ignore any
 215      *           BeanInfo associated with the specified beanClass.
 216      *     If flags == IGNORE_ALL_BEANINFO then we ignore all BeanInfo
 217      *           associated with the specified beanClass or any of its
 218      *           parent classes.
 219      * @return  A BeanInfo object describing the target bean.
 220      * @exception IntrospectionException if an exception occurs during
 221      *              introspection.
 222      * @since 1.2
 223      */
 224     public static BeanInfo getBeanInfo(Class<?> beanClass, int flags)
 225                                                 throws IntrospectionException {
 226         return getBeanInfo(beanClass, null, flags);
 227     }
 228 
 229     /**
 230      * Introspect on a Java bean and learn all about its properties, exposed
 231      * methods, below a given "stop" point.
 232      * <p>
 233      * If the BeanInfo class for a Java Bean has been previously Introspected
 234      * based on the same arguments, then the BeanInfo class is retrieved
 235      * from the BeanInfo cache.
 236      * @return the BeanInfo for the bean
 237      * @param beanClass The bean class to be analyzed.
 238      * @param stopClass The baseclass at which to stop the analysis.  Any
 239      *    methods/properties/events in the stopClass or in its baseclasses
 240      *    will be ignored in the analysis.
 241      * @exception IntrospectionException if an exception occurs during
 242      *              introspection.
 243      */
 244     public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass)
 245                                                 throws IntrospectionException {
 246         return getBeanInfo(beanClass, stopClass, USE_ALL_BEANINFO);
 247     }
 248 
 249     /**
 250      * Introspect on a Java Bean and learn about all its properties,
 251      * exposed methods and events, below a given {@code stopClass} point
 252      * subject to some control {@code flags}.
 253      * <dl>
 254      *  <dt>USE_ALL_BEANINFO</dt>
 255      *  <dd>Any BeanInfo that can be discovered will be used.</dd>
 256      *  <dt>IGNORE_IMMEDIATE_BEANINFO</dt>
 257      *  <dd>Any BeanInfo associated with the specified {@code beanClass} will be ignored.</dd>
 258      *  <dt>IGNORE_ALL_BEANINFO</dt>
 259      *  <dd>Any BeanInfo associated with the specified {@code beanClass}
 260      *      or any of its parent classes will be ignored.</dd>
 261      * </dl>
 262      * Any methods/properties/events in the {@code stopClass}
 263      * or in its parent classes will be ignored in the analysis.
 264      * <p>
 265      * If the BeanInfo class for a Java Bean has been
 266      * previously introspected based on the same arguments then
 267      * the BeanInfo class is retrieved from the BeanInfo cache.
 268      *
 269      * @param beanClass  the bean class to be analyzed
 270      * @param stopClass  the parent class at which to stop the analysis
 271      * @param flags      flags to control the introspection
 272      * @return a BeanInfo object describing the target bean
 273      * @exception IntrospectionException if an exception occurs during introspection
 274      *
 275      * @since 1.7
 276      */
 277     public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass,
 278                                         int flags) throws IntrospectionException {
 279         BeanInfo bi;
 280         if (stopClass == null && flags == USE_ALL_BEANINFO) {
 281             // Same parameters to take advantage of caching.
 282             bi = getBeanInfo(beanClass);
 283         } else {
 284             bi = (new Introspector(beanClass, stopClass, flags)).getBeanInfo();
 285         }
 286         return bi;
 287 
 288         // Old behaviour: Make an independent copy of the BeanInfo.
 289         //return new GenericBeanInfo(bi);
 290     }
 291 
 292 
 293     /**
 294      * Utility method to take a string and convert it to normal Java variable
 295      * name capitalization.  This normally means converting the first
 296      * character from upper case to lower case, but in the (unusual) special
 297      * case when there is more than one character and both the first and
 298      * second characters are upper case, we leave it alone.
 299      * <p>
 300      * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays
 301      * as "URL".
 302      *
 303      * @param  name The string to be decapitalized.
 304      * @return  The decapitalized version of the string.
 305      */
 306     public static String decapitalize(String name) {
 307         if (name == null || name.length() == 0) {
 308             return name;
 309         }
 310         if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
 311                         Character.isUpperCase(name.charAt(0))){
 312             return name;
 313         }
 314         char chars[] = name.toCharArray();
 315         chars[0] = Character.toLowerCase(chars[0]);
 316         return new String(chars);
 317     }
 318 
 319     /**
 320      * Gets the list of package names that will be used for
 321      *          finding BeanInfo classes.
 322      *
 323      * @return  The array of package names that will be searched in
 324      *          order to find BeanInfo classes. The default value
 325      *          for this array is implementation-dependent; e.g.
 326      *          Sun implementation initially sets to {"sun.beans.infos"}.
 327      */
 328 
 329     public static String[] getBeanInfoSearchPath() {
 330         return ThreadGroupContext.getContext().getBeanInfoFinder().getPackages();
 331     }
 332 
 333     /**
 334      * Change the list of package names that will be used for
 335      *          finding BeanInfo classes.  The behaviour of
 336      *          this method is undefined if parameter path
 337      *          is null.
 338      *
 339      * <p>First, if there is a security manager, its <code>checkPropertiesAccess</code>
 340      * method is called. This could result in a SecurityException.
 341      *
 342      * @param path  Array of package names.
 343      * @exception  SecurityException  if a security manager exists and its
 344      *             <code>checkPropertiesAccess</code> method doesn't allow setting
 345      *              of system properties.
 346      * @see SecurityManager#checkPropertiesAccess
 347      */
 348 
 349     public static void setBeanInfoSearchPath(String[] path) {
 350         SecurityManager sm = System.getSecurityManager();
 351         if (sm != null) {
 352             sm.checkPropertiesAccess();
 353         }
 354         ThreadGroupContext.getContext().getBeanInfoFinder().setPackages(path);
 355     }
 356 
 357 
 358     /**
 359      * Flush all of the Introspector's internal caches.  This method is
 360      * not normally required.  It is normally only needed by advanced
 361      * tools that update existing "Class" objects in-place and need
 362      * to make the Introspector re-analyze existing Class objects.
 363      *
 364      * @since 1.2
 365      */
 366 
 367     public static void flushCaches() {
 368         synchronized (declaredMethodCache) {
 369             ThreadGroupContext.getContext().clearBeanInfoCache();
 370             declaredMethodCache.clear();
 371         }
 372     }
 373 
 374     /**
 375      * Flush the Introspector's internal cached information for a given class.
 376      * This method is not normally required.  It is normally only needed
 377      * by advanced tools that update existing "Class" objects in-place
 378      * and need to make the Introspector re-analyze an existing Class object.
 379      *
 380      * Note that only the direct state associated with the target Class
 381      * object is flushed.  We do not flush state for other Class objects
 382      * with the same name, nor do we flush state for any related Class
 383      * objects (such as subclasses), even though their state may include
 384      * information indirectly obtained from the target Class object.
 385      *
 386      * @param clz  Class object to be flushed.
 387      * @throws NullPointerException If the Class object is null.
 388      * @since 1.2
 389      */
 390     public static void flushFromCaches(Class<?> clz) {
 391         if (clz == null) {
 392             throw new NullPointerException();
 393         }
 394         synchronized (declaredMethodCache) {
 395             ThreadGroupContext.getContext().removeBeanInfo(clz);
 396             declaredMethodCache.put(clz, null);
 397         }
 398     }
 399 
 400     //======================================================================
 401     //                  Private implementation methods
 402     //======================================================================
 403 
 404     private Introspector(Class<?> beanClass, Class<?> stopClass, int flags)
 405                                             throws IntrospectionException {
 406         this.beanClass = beanClass;
 407 
 408         // Check stopClass is a superClass of startClass.
 409         if (stopClass != null) {
 410             boolean isSuper = false;
 411             for (Class<?> c = beanClass.getSuperclass(); c != null; c = c.getSuperclass()) {
 412                 if (c == stopClass) {
 413                     isSuper = true;
 414                 }
 415             }
 416             if (!isSuper) {
 417                 throw new IntrospectionException(stopClass.getName() + " not superclass of " +
 418                                         beanClass.getName());
 419             }
 420         }
 421 
 422         if (flags == USE_ALL_BEANINFO) {
 423             explicitBeanInfo = findExplicitBeanInfo(beanClass);
 424         }
 425 
 426         Class<?> superClass = beanClass.getSuperclass();
 427         if (superClass != stopClass) {
 428             int newFlags = flags;
 429             if (newFlags == IGNORE_IMMEDIATE_BEANINFO) {
 430                 newFlags = USE_ALL_BEANINFO;
 431             }
 432             superBeanInfo = getBeanInfo(superClass, stopClass, newFlags);
 433         }
 434         if (explicitBeanInfo != null) {
 435             additionalBeanInfo = explicitBeanInfo.getAdditionalBeanInfo();
 436         }
 437         if (additionalBeanInfo == null) {
 438             additionalBeanInfo = new BeanInfo[0];
 439         }
 440     }
 441 
 442     /**
 443      * Constructs a GenericBeanInfo class from the state of the Introspector
 444      */
 445     private BeanInfo getBeanInfo() throws IntrospectionException {
 446 
 447         // the evaluation order here is import, as we evaluate the
 448         // event sets and locate PropertyChangeListeners before we
 449         // look for properties.
 450         BeanDescriptor bd = getTargetBeanDescriptor();
 451         MethodDescriptor mds[] = getTargetMethodInfo();
 452         EventSetDescriptor esds[] = getTargetEventInfo();
 453         PropertyDescriptor pds[] = getTargetPropertyInfo();
 454 
 455         int defaultEvent = getTargetDefaultEventIndex();
 456         int defaultProperty = getTargetDefaultPropertyIndex();
 457 
 458         return new GenericBeanInfo(bd, esds, defaultEvent, pds,
 459                         defaultProperty, mds, explicitBeanInfo);
 460 
 461     }
 462 
 463     /**
 464      * Looks for an explicit BeanInfo class that corresponds to the Class.
 465      * First it looks in the existing package that the Class is defined in,
 466      * then it checks to see if the class is its own BeanInfo. Finally,
 467      * the BeanInfo search path is prepended to the class and searched.
 468      *
 469      * @param beanClass  the class type of the bean
 470      * @return Instance of an explicit BeanInfo class or null if one isn't found.
 471      */
 472     private static BeanInfo findExplicitBeanInfo(Class<?> beanClass) {
 473         return ThreadGroupContext.getContext().getBeanInfoFinder().find(beanClass);
 474     }
 475 
 476     /**
 477      * @return An array of PropertyDescriptors describing the editable
 478      * properties supported by the target bean.
 479      */
 480 
 481     private PropertyDescriptor[] getTargetPropertyInfo() {
 482 
 483         // Check if the bean has its own BeanInfo that will provide
 484         // explicit information.
 485         PropertyDescriptor[] explicitProperties = null;
 486         if (explicitBeanInfo != null) {
 487             explicitProperties = getPropertyDescriptors(this.explicitBeanInfo);
 488         }
 489 
 490         if (explicitProperties == null && superBeanInfo != null) {
 491             // We have no explicit BeanInfo properties.  Check with our parent.
 492             addPropertyDescriptors(getPropertyDescriptors(this.superBeanInfo));
 493         }
 494 
 495         for (int i = 0; i < additionalBeanInfo.length; i++) {
 496             addPropertyDescriptors(additionalBeanInfo[i].getPropertyDescriptors());
 497         }
 498 
 499         if (explicitProperties != null) {
 500             // Add the explicit BeanInfo data to our results.
 501             addPropertyDescriptors(explicitProperties);
 502 
 503         } else {
 504 
 505             // Apply some reflection to the current class.
 506 
 507             // First get an array of all the public methods at this level
 508             Method methodList[] = getPublicDeclaredMethods(beanClass);
 509 
 510             // Now analyze each method.
 511             for (int i = 0; i < methodList.length; i++) {
 512                 Method method = methodList[i];
 513                 if (method == null) {
 514                     continue;
 515                 }
 516                 // skip static methods.
 517                 int mods = method.getModifiers();
 518                 if (Modifier.isStatic(mods)) {
 519                     continue;
 520                 }
 521                 String name = method.getName();
 522                 Class<?>[] argTypes = method.getParameterTypes();
 523                 Class<?> resultType = method.getReturnType();
 524                 int argCount = argTypes.length;
 525                 PropertyDescriptor pd = null;
 526 
 527                 if (name.length() <= 3 && !name.startsWith(IS_PREFIX)) {
 528                     // Optimization. Don't bother with invalid propertyNames.
 529                     continue;
 530                 }
 531 
 532                 try {
 533 
 534                     if (argCount == 0) {
 535                         if (name.startsWith(GET_PREFIX)) {
 536                             // Simple getter
 537                             pd = new PropertyDescriptor(this.beanClass, name.substring(3), method, null);
 538                         } else if (resultType == boolean.class && name.startsWith(IS_PREFIX)) {
 539                             // Boolean getter
 540                             pd = new PropertyDescriptor(this.beanClass, name.substring(2), method, null);
 541                         }
 542                     } else if (argCount == 1) {
 543                         if (int.class.equals(argTypes[0]) && name.startsWith(GET_PREFIX)) {
 544                             pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, method, null);
 545                         } else if (void.class.equals(resultType) && name.startsWith(SET_PREFIX)) {
 546                             // Simple setter
 547                             pd = new PropertyDescriptor(this.beanClass, name.substring(3), null, method);
 548                             if (throwsException(method, PropertyVetoException.class)) {
 549                                 pd.setConstrained(true);
 550                             }
 551                         }
 552                     } else if (argCount == 2) {
 553                             if (void.class.equals(resultType) && int.class.equals(argTypes[0]) && name.startsWith(SET_PREFIX)) {
 554                             pd = new IndexedPropertyDescriptor(this.beanClass, name.substring(3), null, null, null, method);
 555                             if (throwsException(method, PropertyVetoException.class)) {
 556                                 pd.setConstrained(true);
 557                             }
 558                         }
 559                     }
 560                 } catch (IntrospectionException ex) {
 561                     // This happens if a PropertyDescriptor or IndexedPropertyDescriptor
 562                     // constructor fins that the method violates details of the deisgn
 563                     // pattern, e.g. by having an empty name, or a getter returning
 564                     // void , or whatever.
 565                     pd = null;
 566                 }
 567 
 568                 if (pd != null) {
 569                     // If this class or one of its base classes is a PropertyChange
 570                     // source, then we assume that any properties we discover are "bound".
 571                     if (propertyChangeSource) {
 572                         pd.setBound(true);
 573                     }
 574                     addPropertyDescriptor(pd);
 575                 }
 576             }
 577         }
 578         processPropertyDescriptors();
 579 
 580         // Allocate and populate the result array.
 581         PropertyDescriptor result[] =
 582                 properties.values().toArray(new PropertyDescriptor[properties.size()]);
 583 
 584         // Set the default index.
 585         if (defaultPropertyName != null) {
 586             for (int i = 0; i < result.length; i++) {
 587                 if (defaultPropertyName.equals(result[i].getName())) {
 588                     defaultPropertyIndex = i;
 589                 }
 590             }
 591         }
 592 
 593         return result;
 594     }
 595 
 596     private HashMap<String, List<PropertyDescriptor>> pdStore = new HashMap<>();
 597 
 598     /**
 599      * Adds the property descriptor to the list store.
 600      */
 601     private void addPropertyDescriptor(PropertyDescriptor pd) {
 602         String propName = pd.getName();
 603         List<PropertyDescriptor> list = pdStore.get(propName);
 604         if (list == null) {
 605             list = new ArrayList<>();
 606             pdStore.put(propName, list);
 607         }
 608         if (this.beanClass != pd.getClass0()) {
 609             // replace existing property descriptor
 610             // only if we have types to resolve
 611             // in the context of this.beanClass
 612             Method read = pd.getReadMethod();
 613             Method write = pd.getWriteMethod();
 614             boolean cls = true;
 615             if (read != null) cls = cls && read.getGenericReturnType() instanceof Class;
 616             if (write != null) cls = cls && write.getGenericParameterTypes()[0] instanceof Class;
 617             if (pd instanceof IndexedPropertyDescriptor) {
 618                 IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
 619                 Method readI = ipd.getIndexedReadMethod();
 620                 Method writeI = ipd.getIndexedWriteMethod();
 621                 if (readI != null) cls = cls && readI.getGenericReturnType() instanceof Class;
 622                 if (writeI != null) cls = cls && writeI.getGenericParameterTypes()[1] instanceof Class;
 623                 if (!cls) {
 624                     pd = new IndexedPropertyDescriptor(ipd);
 625                     pd.updateGenericsFor(this.beanClass);
 626                 }
 627             }
 628             else if (!cls) {
 629                 pd = new PropertyDescriptor(pd);
 630                 pd.updateGenericsFor(this.beanClass);
 631             }
 632         }
 633         list.add(pd);
 634     }
 635 
 636     private void addPropertyDescriptors(PropertyDescriptor[] descriptors) {
 637         if (descriptors != null) {
 638             for (PropertyDescriptor descriptor : descriptors) {
 639                 addPropertyDescriptor(descriptor);
 640             }
 641         }
 642     }
 643 
 644     private PropertyDescriptor[] getPropertyDescriptors(BeanInfo info) {
 645         PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
 646         int index = info.getDefaultPropertyIndex();
 647         if ((0 <= index) && (index < descriptors.length)) {
 648             this.defaultPropertyName = descriptors[index].getName();
 649         }
 650         return descriptors;
 651     }
 652 
 653     /**
 654      * Populates the property descriptor table by merging the
 655      * lists of Property descriptors.
 656      */
 657     private void processPropertyDescriptors() {
 658         if (properties == null) {
 659             properties = new TreeMap<>();
 660         }
 661 
 662         List<PropertyDescriptor> list;
 663 
 664         PropertyDescriptor pd, gpd, spd;
 665         IndexedPropertyDescriptor ipd, igpd, ispd;
 666 
 667         Iterator<List<PropertyDescriptor>> it = pdStore.values().iterator();
 668         while (it.hasNext()) {
 669             pd = null; gpd = null; spd = null;
 670             ipd = null; igpd = null; ispd = null;
 671 
 672             list = it.next();
 673 
 674             // First pass. Find the latest getter method. Merge properties
 675             // of previous getter methods.
 676             for (int i = 0; i < list.size(); i++) {
 677                 pd = list.get(i);
 678                 if (pd instanceof IndexedPropertyDescriptor) {
 679                     ipd = (IndexedPropertyDescriptor)pd;
 680                     if (ipd.getIndexedReadMethod() != null) {
 681                         if (igpd != null) {
 682                             igpd = new IndexedPropertyDescriptor(igpd, ipd);
 683                         } else {
 684                             igpd = ipd;
 685                         }
 686                     }
 687                 } else {
 688                     if (pd.getReadMethod() != null) {
 689                         String pdName = pd.getReadMethod().getName();
 690                         if (gpd != null) {
 691                             // Don't replace the existing read
 692                             // method if it starts with "is"
 693                             String gpdName = gpd.getReadMethod().getName();
 694                             if (gpdName.equals(pdName) || !gpdName.startsWith(IS_PREFIX)) {
 695                                 gpd = new PropertyDescriptor(gpd, pd);
 696                             }
 697                         } else {
 698                             gpd = pd;
 699                         }
 700                     }
 701                 }
 702             }
 703 
 704             // Second pass. Find the latest setter method which
 705             // has the same type as the getter method.
 706             for (int i = 0; i < list.size(); i++) {
 707                 pd = list.get(i);
 708                 if (pd instanceof IndexedPropertyDescriptor) {
 709                     ipd = (IndexedPropertyDescriptor)pd;
 710                     if (ipd.getIndexedWriteMethod() != null) {
 711                         if (igpd != null) {
 712                             if (isAssignable(igpd.getIndexedPropertyType(), ipd.getIndexedPropertyType())) {
 713                                 if (ispd != null) {
 714                                     ispd = new IndexedPropertyDescriptor(ispd, ipd);
 715                                 } else {
 716                                     ispd = ipd;
 717                                 }
 718                             }
 719                         } else {
 720                             if (ispd != null) {
 721                                 ispd = new IndexedPropertyDescriptor(ispd, ipd);
 722                             } else {
 723                                 ispd = ipd;
 724                             }
 725                         }
 726                     }
 727                 } else {
 728                     if (pd.getWriteMethod() != null) {
 729                         if (gpd != null) {
 730                             if (isAssignable(gpd.getPropertyType(), pd.getPropertyType())) {
 731                                 if (spd != null) {
 732                                     spd = new PropertyDescriptor(spd, pd);
 733                                 } else {
 734                                     spd = pd;
 735                                 }
 736                             }
 737                         } else {
 738                             if (spd != null) {
 739                                 spd = new PropertyDescriptor(spd, pd);
 740                             } else {
 741                                 spd = pd;
 742                             }
 743                         }
 744                     }
 745                 }
 746             }
 747 
 748             // At this stage we should have either PDs or IPDs for the
 749             // representative getters and setters. The order at which the
 750             // property descriptors are determined represent the
 751             // precedence of the property ordering.
 752             pd = null; ipd = null;
 753 
 754             if (igpd != null && ispd != null) {
 755                 // Complete indexed properties set
 756                 // Merge any classic property descriptors
 757                 if ((gpd == spd) || (gpd == null)) {
 758                     pd = spd;
 759                 } else if (spd == null) {
 760                     pd = gpd;
 761                 } else if (spd instanceof IndexedPropertyDescriptor) {
 762                     pd = mergePropertyWithIndexedProperty(gpd, (IndexedPropertyDescriptor) spd);
 763                 } else if (gpd instanceof IndexedPropertyDescriptor) {
 764                     pd = mergePropertyWithIndexedProperty(spd, (IndexedPropertyDescriptor) gpd);
 765                 } else {
 766                     pd = mergePropertyDescriptor(gpd, spd);
 767                 }
 768                 if (igpd == ispd) {
 769                     ipd = igpd;
 770                 } else {
 771                     ipd = mergePropertyDescriptor(igpd, ispd);
 772                 }
 773                 if (pd == null) {
 774                     pd = ipd;
 775                 } else {
 776                     Class<?> propType = pd.getPropertyType();
 777                     Class<?> ipropType = ipd.getIndexedPropertyType();
 778                     if (propType.isArray() && propType.getComponentType() == ipropType) {
 779                         pd = pd.getClass0().isAssignableFrom(ipd.getClass0())
 780                                 ? new IndexedPropertyDescriptor(pd, ipd)
 781                                 : new IndexedPropertyDescriptor(ipd, pd);
 782                     } else if (pd.getClass0().isAssignableFrom(ipd.getClass0())) {
 783                         pd = pd.getClass0().isAssignableFrom(ipd.getClass0())
 784                                 ? new PropertyDescriptor(pd, ipd)
 785                                 : new PropertyDescriptor(ipd, pd);
 786                     } else {
 787                         pd = ipd;
 788                     }
 789                 }
 790             } else if (gpd != null && spd != null) {
 791                 if (igpd != null) {
 792                     gpd = mergePropertyWithIndexedProperty(gpd, igpd);
 793                 }
 794                 if (ispd != null) {
 795                     spd = mergePropertyWithIndexedProperty(spd, ispd);
 796                 }
 797                 // Complete simple properties set
 798                 if (gpd == spd) {
 799                     pd = gpd;
 800                 } else if (spd instanceof IndexedPropertyDescriptor) {
 801                     pd = mergePropertyWithIndexedProperty(gpd, (IndexedPropertyDescriptor) spd);
 802                 } else if (gpd instanceof IndexedPropertyDescriptor) {
 803                     pd = mergePropertyWithIndexedProperty(spd, (IndexedPropertyDescriptor) gpd);
 804                 } else {
 805                     pd = mergePropertyDescriptor(gpd, spd);
 806                 }
 807             } else if (ispd != null) {
 808                 // indexed setter
 809                 pd = ispd;
 810                 // Merge any classic property descriptors
 811                 if (spd != null) {
 812                     pd = mergePropertyDescriptor(ispd, spd);
 813                 }
 814                 if (gpd != null) {
 815                     pd = mergePropertyDescriptor(ispd, gpd);
 816                 }
 817             } else if (igpd != null) {
 818                 // indexed getter
 819                 pd = igpd;
 820                 // Merge any classic property descriptors
 821                 if (gpd != null) {
 822                     pd = mergePropertyDescriptor(igpd, gpd);
 823                 }
 824                 if (spd != null) {
 825                     pd = mergePropertyDescriptor(igpd, spd);
 826                 }
 827             } else if (spd != null) {
 828                 // simple setter
 829                 pd = spd;
 830             } else if (gpd != null) {
 831                 // simple getter
 832                 pd = gpd;
 833             }
 834 
 835             // Very special case to ensure that an IndexedPropertyDescriptor
 836             // doesn't contain less information than the enclosed
 837             // PropertyDescriptor. If it does, then recreate as a
 838             // PropertyDescriptor. See 4168833
 839             if (pd instanceof IndexedPropertyDescriptor) {
 840                 ipd = (IndexedPropertyDescriptor)pd;
 841                 if (ipd.getIndexedReadMethod() == null && ipd.getIndexedWriteMethod() == null) {
 842                     pd = new PropertyDescriptor(ipd);
 843                 }
 844             }
 845 
 846             // Find the first property descriptor
 847             // which does not have getter and setter methods.
 848             // See regression bug 4984912.
 849             if ( (pd == null) && (list.size() > 0) ) {
 850                 pd = list.get(0);
 851             }
 852 
 853             if (pd != null) {
 854                 properties.put(pd.getName(), pd);
 855             }
 856         }
 857     }
 858 
 859     private static boolean isAssignable(Class<?> current, Class<?> candidate) {
 860         return ((current == null) || (candidate == null)) ? current == candidate : current.isAssignableFrom(candidate);
 861     }
 862 
 863     private PropertyDescriptor mergePropertyWithIndexedProperty(PropertyDescriptor pd, IndexedPropertyDescriptor ipd) {
 864         Class<?> type = pd.getPropertyType();
 865         if (type.isArray() && (type.getComponentType() == ipd.getIndexedPropertyType())) {
 866             return pd.getClass0().isAssignableFrom(ipd.getClass0())
 867                     ? new IndexedPropertyDescriptor(pd, ipd)
 868                     : new IndexedPropertyDescriptor(ipd, pd);
 869         }
 870         return pd;
 871     }
 872 
 873     /**
 874      * Adds the property descriptor to the indexedproperty descriptor only if the
 875      * types are the same.
 876      *
 877      * The most specific property descriptor will take precedence.
 878      */
 879     private PropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd,
 880                                                        PropertyDescriptor pd) {
 881         PropertyDescriptor result = null;
 882 
 883         Class<?> propType = pd.getPropertyType();
 884         Class<?> ipropType = ipd.getIndexedPropertyType();
 885 
 886         if (propType.isArray() && propType.getComponentType() == ipropType) {
 887             if (pd.getClass0().isAssignableFrom(ipd.getClass0())) {
 888                 result = new IndexedPropertyDescriptor(pd, ipd);
 889             } else {
 890                 result = new IndexedPropertyDescriptor(ipd, pd);
 891             }
 892         } else if ((ipd.getReadMethod() == null) && (ipd.getWriteMethod() == null)) {
 893             if (pd.getClass0().isAssignableFrom(ipd.getClass0())) {
 894                 result = new PropertyDescriptor(pd, ipd);
 895             } else {
 896                 result = new PropertyDescriptor(ipd, pd);
 897             }
 898         } else {
 899             // Cannot merge the pd because of type mismatch
 900             // Return the most specific pd
 901             if (pd.getClass0().isAssignableFrom(ipd.getClass0())) {
 902                 result = ipd;
 903             } else {
 904                 result = pd;
 905                 // Try to add methods which may have been lost in the type change
 906                 // See 4168833
 907                 Method write = result.getWriteMethod();
 908                 Method read = result.getReadMethod();
 909 
 910                 if (read == null && write != null) {
 911                     read = findMethod(result.getClass0(),
 912                                       GET_PREFIX + NameGenerator.capitalize(result.getName()), 0);
 913                     if (read != null) {
 914                         try {
 915                             result.setReadMethod(read);
 916                         } catch (IntrospectionException ex) {
 917                             // no consequences for failure.
 918                         }
 919                     }
 920                 }
 921                 if (write == null && read != null) {
 922                     write = findMethod(result.getClass0(),
 923                                        SET_PREFIX + NameGenerator.capitalize(result.getName()), 1,
 924                                        new Class<?>[] { FeatureDescriptor.getReturnType(result.getClass0(), read) });
 925                     if (write != null) {
 926                         try {
 927                             result.setWriteMethod(write);
 928                         } catch (IntrospectionException ex) {
 929                             // no consequences for failure.
 930                         }
 931                     }
 932                 }
 933             }
 934         }
 935         return result;
 936     }
 937 
 938     // Handle regular pd merge
 939     private PropertyDescriptor mergePropertyDescriptor(PropertyDescriptor pd1,
 940                                                        PropertyDescriptor pd2) {
 941         if (pd1.getClass0().isAssignableFrom(pd2.getClass0())) {
 942             return new PropertyDescriptor(pd1, pd2);
 943         } else {
 944             return new PropertyDescriptor(pd2, pd1);
 945         }
 946     }
 947 
 948     // Handle regular ipd merge
 949     private IndexedPropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd1,
 950                                                        IndexedPropertyDescriptor ipd2) {
 951         if (ipd1.getClass0().isAssignableFrom(ipd2.getClass0())) {
 952             return new IndexedPropertyDescriptor(ipd1, ipd2);
 953         } else {
 954             return new IndexedPropertyDescriptor(ipd2, ipd1);
 955         }
 956     }
 957 
 958     /**
 959      * @return An array of EventSetDescriptors describing the kinds of
 960      * events fired by the target bean.
 961      */
 962     private EventSetDescriptor[] getTargetEventInfo() throws IntrospectionException {
 963         if (events == null) {
 964             events = new HashMap<>();
 965         }
 966 
 967         // Check if the bean has its own BeanInfo that will provide
 968         // explicit information.
 969         EventSetDescriptor[] explicitEvents = null;
 970         if (explicitBeanInfo != null) {
 971             explicitEvents = explicitBeanInfo.getEventSetDescriptors();
 972             int ix = explicitBeanInfo.getDefaultEventIndex();
 973             if (ix >= 0 && ix < explicitEvents.length) {
 974                 defaultEventName = explicitEvents[ix].getName();
 975             }
 976         }
 977 
 978         if (explicitEvents == null && superBeanInfo != null) {
 979             // We have no explicit BeanInfo events.  Check with our parent.
 980             EventSetDescriptor supers[] = superBeanInfo.getEventSetDescriptors();
 981             for (int i = 0 ; i < supers.length; i++) {
 982                 addEvent(supers[i]);
 983             }
 984             int ix = superBeanInfo.getDefaultEventIndex();
 985             if (ix >= 0 && ix < supers.length) {
 986                 defaultEventName = supers[ix].getName();
 987             }
 988         }
 989 
 990         for (int i = 0; i < additionalBeanInfo.length; i++) {
 991             EventSetDescriptor additional[] = additionalBeanInfo[i].getEventSetDescriptors();
 992             if (additional != null) {
 993                 for (int j = 0 ; j < additional.length; j++) {
 994                     addEvent(additional[j]);
 995                 }
 996             }
 997         }
 998 
 999         if (explicitEvents != null) {
1000             // Add the explicit explicitBeanInfo data to our results.
1001             for (int i = 0 ; i < explicitEvents.length; i++) {
1002                 addEvent(explicitEvents[i]);
1003             }
1004 
1005         } else {
1006 
1007             // Apply some reflection to the current class.
1008 
1009             // Get an array of all the public beans methods at this level
1010             Method methodList[] = getPublicDeclaredMethods(beanClass);
1011 
1012             // Find all suitable "add", "remove" and "get" Listener methods
1013             // The name of the listener type is the key for these hashtables
1014             // i.e, ActionListener
1015             Map<String, Method> adds = null;
1016             Map<String, Method> removes = null;
1017             Map<String, Method> gets = null;
1018 
1019             for (int i = 0; i < methodList.length; i++) {
1020                 Method method = methodList[i];
1021                 if (method == null) {
1022                     continue;
1023                 }
1024                 // skip static methods.
1025                 int mods = method.getModifiers();
1026                 if (Modifier.isStatic(mods)) {
1027                     continue;
1028                 }
1029                 String name = method.getName();
1030                 // Optimization avoid getParameterTypes
1031                 if (!name.startsWith(ADD_PREFIX) && !name.startsWith(REMOVE_PREFIX)
1032                     && !name.startsWith(GET_PREFIX)) {
1033                     continue;
1034                 }
1035 
1036                 if (name.startsWith(ADD_PREFIX)) {
1037                     Class<?> returnType = method.getReturnType();
1038                     if (returnType == void.class) {
1039                         Type[] parameterTypes = method.getGenericParameterTypes();
1040                         if (parameterTypes.length == 1) {
1041                             Class<?> type = TypeResolver.erase(TypeResolver.resolveInClass(beanClass, parameterTypes[0]));
1042                             if (Introspector.isSubclass(type, eventListenerType)) {
1043                                 String listenerName = name.substring(3);
1044                                 if (listenerName.length() > 0 &&
1045                                     type.getName().endsWith(listenerName)) {
1046                                     if (adds == null) {
1047                                         adds = new HashMap<>();
1048                                     }
1049                                     adds.put(listenerName, method);
1050                                 }
1051                             }
1052                         }
1053                     }
1054                 }
1055                 else if (name.startsWith(REMOVE_PREFIX)) {
1056                     Class<?> returnType = method.getReturnType();
1057                     if (returnType == void.class) {
1058                         Type[] parameterTypes = method.getGenericParameterTypes();
1059                         if (parameterTypes.length == 1) {
1060                             Class<?> type = TypeResolver.erase(TypeResolver.resolveInClass(beanClass, parameterTypes[0]));
1061                             if (Introspector.isSubclass(type, eventListenerType)) {
1062                                 String listenerName = name.substring(6);
1063                                 if (listenerName.length() > 0 &&
1064                                     type.getName().endsWith(listenerName)) {
1065                                     if (removes == null) {
1066                                         removes = new HashMap<>();
1067                                     }
1068                                     removes.put(listenerName, method);
1069                                 }
1070                             }
1071                         }
1072                     }
1073                 }
1074                 else if (name.startsWith(GET_PREFIX)) {
1075                     Class<?>[] parameterTypes = method.getParameterTypes();
1076                     if (parameterTypes.length == 0) {
1077                         Class<?> returnType = FeatureDescriptor.getReturnType(beanClass, method);
1078                         if (returnType.isArray()) {
1079                             Class<?> type = returnType.getComponentType();
1080                             if (Introspector.isSubclass(type, eventListenerType)) {
1081                                 String listenerName  = name.substring(3, name.length() - 1);
1082                                 if (listenerName.length() > 0 &&
1083                                     type.getName().endsWith(listenerName)) {
1084                                     if (gets == null) {
1085                                         gets = new HashMap<>();
1086                                     }
1087                                     gets.put(listenerName, method);
1088                                 }
1089                             }
1090                         }
1091                     }
1092                 }
1093             }
1094 
1095             if (adds != null && removes != null) {
1096                 // Now look for matching addFooListener+removeFooListener pairs.
1097                 // Bonus if there is a matching getFooListeners method as well.
1098                 Iterator<String> keys = adds.keySet().iterator();
1099                 while (keys.hasNext()) {
1100                     String listenerName = keys.next();
1101                     // Skip any "add" which doesn't have a matching "remove" or
1102                     // a listener name that doesn't end with Listener
1103                     if (removes.get(listenerName) == null || !listenerName.endsWith("Listener")) {
1104                         continue;
1105                     }
1106                     String eventName = decapitalize(listenerName.substring(0, listenerName.length()-8));
1107                     Method addMethod = adds.get(listenerName);
1108                     Method removeMethod = removes.get(listenerName);
1109                     Method getMethod = null;
1110                     if (gets != null) {
1111                         getMethod = gets.get(listenerName);
1112                     }
1113                     Class<?> argType = FeatureDescriptor.getParameterTypes(beanClass, addMethod)[0];
1114 
1115                     // generate a list of Method objects for each of the target methods:
1116                     Method allMethods[] = getPublicDeclaredMethods(argType);
1117                     List<Method> validMethods = new ArrayList<>(allMethods.length);
1118                     for (int i = 0; i < allMethods.length; i++) {
1119                         if (allMethods[i] == null) {
1120                             continue;
1121                         }
1122 
1123                         if (isEventHandler(allMethods[i])) {
1124                             validMethods.add(allMethods[i]);
1125                         }
1126                     }
1127                     Method[] methods = validMethods.toArray(new Method[validMethods.size()]);
1128 
1129                     EventSetDescriptor esd = new EventSetDescriptor(eventName, argType,
1130                                                                     methods, addMethod,
1131                                                                     removeMethod,
1132                                                                     getMethod);
1133 
1134                     // If the adder method throws the TooManyListenersException then it
1135                     // is a Unicast event source.
1136                     if (throwsException(addMethod,
1137                                         java.util.TooManyListenersException.class)) {
1138                         esd.setUnicast(true);
1139                     }
1140                     addEvent(esd);
1141                 }
1142             } // if (adds != null ...
1143         }
1144         EventSetDescriptor[] result;
1145         if (events.size() == 0) {
1146             result = EMPTY_EVENTSETDESCRIPTORS;
1147         } else {
1148             // Allocate and populate the result array.
1149             result = new EventSetDescriptor[events.size()];
1150             result = events.values().toArray(result);
1151 
1152             // Set the default index.
1153             if (defaultEventName != null) {
1154                 for (int i = 0; i < result.length; i++) {
1155                     if (defaultEventName.equals(result[i].getName())) {
1156                         defaultEventIndex = i;
1157                     }
1158                 }
1159             }
1160         }
1161         return result;
1162     }
1163 
1164     private void addEvent(EventSetDescriptor esd) {
1165         String key = esd.getName();
1166         if (esd.getName().equals("propertyChange")) {
1167             propertyChangeSource = true;
1168         }
1169         EventSetDescriptor old = events.get(key);
1170         if (old == null) {
1171             events.put(key, esd);
1172             return;
1173         }
1174         EventSetDescriptor composite = new EventSetDescriptor(old, esd);
1175         events.put(key, composite);
1176     }
1177 
1178     /**
1179      * @return An array of MethodDescriptors describing the private
1180      * methods supported by the target bean.
1181      */
1182     private MethodDescriptor[] getTargetMethodInfo() {
1183         if (methods == null) {
1184             methods = new HashMap<>(100);
1185         }
1186 
1187         // Check if the bean has its own BeanInfo that will provide
1188         // explicit information.
1189         MethodDescriptor[] explicitMethods = null;
1190         if (explicitBeanInfo != null) {
1191             explicitMethods = explicitBeanInfo.getMethodDescriptors();
1192         }
1193 
1194         if (explicitMethods == null && superBeanInfo != null) {
1195             // We have no explicit BeanInfo methods.  Check with our parent.
1196             MethodDescriptor supers[] = superBeanInfo.getMethodDescriptors();
1197             for (int i = 0 ; i < supers.length; i++) {
1198                 addMethod(supers[i]);
1199             }
1200         }
1201 
1202         for (int i = 0; i < additionalBeanInfo.length; i++) {
1203             MethodDescriptor additional[] = additionalBeanInfo[i].getMethodDescriptors();
1204             if (additional != null) {
1205                 for (int j = 0 ; j < additional.length; j++) {
1206                     addMethod(additional[j]);
1207                 }
1208             }
1209         }
1210 
1211         if (explicitMethods != null) {
1212             // Add the explicit explicitBeanInfo data to our results.
1213             for (int i = 0 ; i < explicitMethods.length; i++) {
1214                 addMethod(explicitMethods[i]);
1215             }
1216 
1217         } else {
1218 
1219             // Apply some reflection to the current class.
1220 
1221             // First get an array of all the beans methods at this level
1222             Method methodList[] = getPublicDeclaredMethods(beanClass);
1223 
1224             // Now analyze each method.
1225             for (int i = 0; i < methodList.length; i++) {
1226                 Method method = methodList[i];
1227                 if (method == null) {
1228                     continue;
1229                 }
1230                 MethodDescriptor md = new MethodDescriptor(method);
1231                 addMethod(md);
1232             }
1233         }
1234 
1235         // Allocate and populate the result array.
1236         MethodDescriptor result[] = new MethodDescriptor[methods.size()];
1237         result = methods.values().toArray(result);
1238 
1239         return result;
1240     }
1241 
1242     private void addMethod(MethodDescriptor md) {
1243         // We have to be careful here to distinguish method by both name
1244         // and argument lists.
1245         // This method gets called a *lot, so we try to be efficient.
1246         String name = md.getName();
1247 
1248         MethodDescriptor old = methods.get(name);
1249         if (old == null) {
1250             // This is the common case.
1251             methods.put(name, md);
1252             return;
1253         }
1254 
1255         // We have a collision on method names.  This is rare.
1256 
1257         // Check if old and md have the same type.
1258         String[] p1 = md.getParamNames();
1259         String[] p2 = old.getParamNames();
1260 
1261         boolean match = false;
1262         if (p1.length == p2.length) {
1263             match = true;
1264             for (int i = 0; i < p1.length; i++) {
1265                 if (p1[i] != p2[i]) {
1266                     match = false;
1267                     break;
1268                 }
1269             }
1270         }
1271         if (match) {
1272             MethodDescriptor composite = new MethodDescriptor(old, md);
1273             methods.put(name, composite);
1274             return;
1275         }
1276 
1277         // We have a collision on method names with different type signatures.
1278         // This is very rare.
1279 
1280         String longKey = makeQualifiedMethodName(name, p1);
1281         old = methods.get(longKey);
1282         if (old == null) {
1283             methods.put(longKey, md);
1284             return;
1285         }
1286         MethodDescriptor composite = new MethodDescriptor(old, md);
1287         methods.put(longKey, composite);
1288     }
1289 
1290     /**
1291      * Creates a key for a method in a method cache.
1292      */
1293     private static String makeQualifiedMethodName(String name, String[] params) {
1294         StringBuffer sb = new StringBuffer(name);
1295         sb.append('=');
1296         for (int i = 0; i < params.length; i++) {
1297             sb.append(':');
1298             sb.append(params[i]);
1299         }
1300         return sb.toString();
1301     }
1302 
1303     private int getTargetDefaultEventIndex() {
1304         return defaultEventIndex;
1305     }
1306 
1307     private int getTargetDefaultPropertyIndex() {
1308         return defaultPropertyIndex;
1309     }
1310 
1311     private BeanDescriptor getTargetBeanDescriptor() {
1312         // Use explicit info, if available,
1313         if (explicitBeanInfo != null) {
1314             BeanDescriptor bd = explicitBeanInfo.getBeanDescriptor();
1315             if (bd != null) {
1316                 return (bd);
1317             }
1318         }
1319         // OK, fabricate a default BeanDescriptor.
1320         return new BeanDescriptor(this.beanClass, findCustomizerClass(this.beanClass));
1321     }
1322 
1323     private static Class<?> findCustomizerClass(Class<?> type) {
1324         String name = type.getName() + "Customizer";
1325         try {
1326             type = ClassFinder.findClass(name, type.getClassLoader());
1327             // Each customizer should inherit java.awt.Component and implement java.beans.Customizer
1328             // according to the section 9.3 of JavaBeans&trade; specification
1329             if (Component.class.isAssignableFrom(type) && Customizer.class.isAssignableFrom(type)) {
1330                 return type;
1331             }
1332         }
1333         catch (Exception exception) {
1334             // ignore any exceptions
1335         }
1336         return null;
1337     }
1338 
1339     private boolean isEventHandler(Method m) {
1340         // We assume that a method is an event handler if it has a single
1341         // argument, whose type inherit from java.util.Event.
1342         Type argTypes[] = m.getGenericParameterTypes();
1343         if (argTypes.length != 1) {
1344             return false;
1345         }
1346         return isSubclass(TypeResolver.erase(TypeResolver.resolveInClass(beanClass, argTypes[0])), EventObject.class);
1347     }
1348 
1349     /*
1350      * Internal method to return *public* methods within a class.
1351      */
1352     private static Method[] getPublicDeclaredMethods(Class<?> clz) {
1353         // Looking up Class.getDeclaredMethods is relatively expensive,
1354         // so we cache the results.
1355         if (!ReflectUtil.isPackageAccessible(clz)) {
1356             return new Method[0];
1357         }
1358         synchronized (declaredMethodCache) {
1359             Method[] result = declaredMethodCache.get(clz);
1360             if (result == null) {
1361                 result = clz.getMethods();
1362                 for (int i = 0; i < result.length; i++) {
1363                     Method method = result[i];
1364                     if (!method.getDeclaringClass().equals(clz)) {
1365                         result[i] = null; // ignore methods declared elsewhere
1366                     }
1367                     else {
1368                         try {
1369                             method = MethodFinder.findAccessibleMethod(method);
1370                             Class<?> type = method.getDeclaringClass();
1371                             result[i] = type.equals(clz) || type.isInterface()
1372                                     ? method
1373                                     : null; // ignore methods from superclasses
1374                         }
1375                         catch (NoSuchMethodException exception) {
1376                             // commented out because of 6976577
1377                             // result[i] = null; // ignore inaccessible methods
1378                         }
1379                     }
1380                 }
1381                 declaredMethodCache.put(clz, result);
1382             }
1383             return result;
1384         }
1385     }
1386 
1387     //======================================================================
1388     // Package private support methods.
1389     //======================================================================
1390 
1391     /**
1392      * Internal support for finding a target methodName with a given
1393      * parameter list on a given class.
1394      */
1395     private static Method internalFindMethod(Class<?> start, String methodName,
1396                                                  int argCount, Class<?> args[]) {
1397         // For overriden methods we need to find the most derived version.
1398         // So we start with the given class and walk up the superclass chain.
1399 
1400         Method method = null;
1401 
1402         for (Class<?> cl = start; cl != null; cl = cl.getSuperclass()) {
1403             Method methods[] = getPublicDeclaredMethods(cl);
1404             for (int i = 0; i < methods.length; i++) {
1405                 method = methods[i];
1406                 if (method == null) {
1407                     continue;
1408                 }
1409 
1410                 // make sure method signature matches.
1411                 if (method.getName().equals(methodName)) {
1412                     Type[] params = method.getGenericParameterTypes();
1413                     if (params.length == argCount) {
1414                         if (args != null) {
1415                             boolean different = false;
1416                             if (argCount > 0) {
1417                                 for (int j = 0; j < argCount; j++) {
1418                                     if (TypeResolver.erase(TypeResolver.resolveInClass(start, params[j])) != args[j]) {
1419                                         different = true;
1420                                         continue;
1421                                     }
1422                                 }
1423                                 if (different) {
1424                                     continue;
1425                                 }
1426                             }
1427                         }
1428                         return method;
1429                     }
1430                 }
1431             }
1432         }
1433         method = null;
1434 
1435         // Now check any inherited interfaces.  This is necessary both when
1436         // the argument class is itself an interface, and when the argument
1437         // class is an abstract class.
1438         Class<?>[] ifcs = start.getInterfaces();
1439         for (int i = 0 ; i < ifcs.length; i++) {
1440             // Note: The original implementation had both methods calling
1441             // the 3 arg method. This is preserved but perhaps it should
1442             // pass the args array instead of null.
1443             method = internalFindMethod(ifcs[i], methodName, argCount, null);
1444             if (method != null) {
1445                 break;
1446             }
1447         }
1448         return method;
1449     }
1450 
1451     /**
1452      * Find a target methodName on a given class.
1453      */
1454     static Method findMethod(Class<?> cls, String methodName, int argCount) {
1455         return findMethod(cls, methodName, argCount, null);
1456     }
1457 
1458     /**
1459      * Find a target methodName with specific parameter list on a given class.
1460      * <p>
1461      * Used in the contructors of the EventSetDescriptor,
1462      * PropertyDescriptor and the IndexedPropertyDescriptor.
1463      * <p>
1464      * @param cls The Class object on which to retrieve the method.
1465      * @param methodName Name of the method.
1466      * @param argCount Number of arguments for the desired method.
1467      * @param args Array of argument types for the method.
1468      * @return the method or null if not found
1469      */
1470     static Method findMethod(Class<?> cls, String methodName, int argCount,
1471                              Class<?>[] args) {
1472         if (methodName == null) {
1473             return null;
1474         }
1475         return internalFindMethod(cls, methodName, argCount, args);
1476     }
1477 
1478     /**
1479      * Return true if class a is either equivalent to class b, or
1480      * if class a is a subclass of class b, i.e. if a either "extends"
1481      * or "implements" b.
1482      * Note tht either or both "Class" objects may represent interfaces.
1483      */
1484     static  boolean isSubclass(Class<?> a, Class<?> b) {
1485         // We rely on the fact that for any given java class or
1486         // primtitive type there is a unqiue Class object, so
1487         // we can use object equivalence in the comparisons.
1488         if (a == b) {
1489             return true;
1490         }
1491         if (a == null || b == null) {
1492             return false;
1493         }
1494         for (Class<?> x = a; x != null; x = x.getSuperclass()) {
1495             if (x == b) {
1496                 return true;
1497             }
1498             if (b.isInterface()) {
1499                 Class<?>[] interfaces = x.getInterfaces();
1500                 for (int i = 0; i < interfaces.length; i++) {
1501                     if (isSubclass(interfaces[i], b)) {
1502                         return true;
1503                     }
1504                 }
1505             }
1506         }
1507         return false;
1508     }
1509 
1510     /**
1511      * Return true iff the given method throws the given exception.
1512      */
1513     private boolean throwsException(Method method, Class<?> exception) {
1514         Class<?>[] exs = method.getExceptionTypes();
1515         for (int i = 0; i < exs.length; i++) {
1516             if (exs[i] == exception) {
1517                 return true;
1518             }
1519         }
1520         return false;
1521     }
1522 
1523     /**
1524      * Try to create an instance of a named class.
1525      * First try the classloader of "sibling", then try the system
1526      * classloader then the class loader of the current Thread.
1527      */
1528     static Object instantiate(Class<?> sibling, String className)
1529                  throws InstantiationException, IllegalAccessException,
1530                                                 ClassNotFoundException {
1531         // First check with sibling's classloader (if any).
1532         ClassLoader cl = sibling.getClassLoader();
1533         Class<?> cls = ClassFinder.findClass(className, cl);
1534         return cls.newInstance();
1535     }
1536 
1537 } // end class Introspector
1538 
1539 //===========================================================================
1540 
1541 /**
1542  * Package private implementation support class for Introspector's
1543  * internal use.
1544  * <p>
1545  * Mostly this is used as a placeholder for the descriptors.
1546  */
1547 
1548 class GenericBeanInfo extends SimpleBeanInfo {
1549 
1550     private BeanDescriptor beanDescriptor;
1551     private EventSetDescriptor[] events;
1552     private int defaultEvent;
1553     private PropertyDescriptor[] properties;
1554     private int defaultProperty;
1555     private MethodDescriptor[] methods;
1556     private Reference<BeanInfo> targetBeanInfoRef;
1557 
1558     public GenericBeanInfo(BeanDescriptor beanDescriptor,
1559                 EventSetDescriptor[] events, int defaultEvent,
1560                 PropertyDescriptor[] properties, int defaultProperty,
1561                 MethodDescriptor[] methods, BeanInfo targetBeanInfo) {
1562         this.beanDescriptor = beanDescriptor;
1563         this.events = events;
1564         this.defaultEvent = defaultEvent;
1565         this.properties = properties;
1566         this.defaultProperty = defaultProperty;
1567         this.methods = methods;
1568         this.targetBeanInfoRef = (targetBeanInfo != null)
1569                 ? new SoftReference<>(targetBeanInfo)
1570                 : null;
1571     }
1572 
1573     /**
1574      * Package-private dup constructor
1575      * This must isolate the new object from any changes to the old object.
1576      */
1577     GenericBeanInfo(GenericBeanInfo old) {
1578 
1579         beanDescriptor = new BeanDescriptor(old.beanDescriptor);
1580         if (old.events != null) {
1581             int len = old.events.length;
1582             events = new EventSetDescriptor[len];
1583             for (int i = 0; i < len; i++) {
1584                 events[i] = new EventSetDescriptor(old.events[i]);
1585             }
1586         }
1587         defaultEvent = old.defaultEvent;
1588         if (old.properties != null) {
1589             int len = old.properties.length;
1590             properties = new PropertyDescriptor[len];
1591             for (int i = 0; i < len; i++) {
1592                 PropertyDescriptor oldp = old.properties[i];
1593                 if (oldp instanceof IndexedPropertyDescriptor) {
1594                     properties[i] = new IndexedPropertyDescriptor(
1595                                         (IndexedPropertyDescriptor) oldp);
1596                 } else {
1597                     properties[i] = new PropertyDescriptor(oldp);
1598                 }
1599             }
1600         }
1601         defaultProperty = old.defaultProperty;
1602         if (old.methods != null) {
1603             int len = old.methods.length;
1604             methods = new MethodDescriptor[len];
1605             for (int i = 0; i < len; i++) {
1606                 methods[i] = new MethodDescriptor(old.methods[i]);
1607             }
1608         }
1609         this.targetBeanInfoRef = old.targetBeanInfoRef;
1610     }
1611 
1612     public PropertyDescriptor[] getPropertyDescriptors() {
1613         return properties;
1614     }
1615 
1616     public int getDefaultPropertyIndex() {
1617         return defaultProperty;
1618     }
1619 
1620     public EventSetDescriptor[] getEventSetDescriptors() {
1621         return events;
1622     }
1623 
1624     public int getDefaultEventIndex() {
1625         return defaultEvent;
1626     }
1627 
1628     public MethodDescriptor[] getMethodDescriptors() {
1629         return methods;
1630     }
1631 
1632     public BeanDescriptor getBeanDescriptor() {
1633         return beanDescriptor;
1634     }
1635 
1636     public java.awt.Image getIcon(int iconKind) {
1637         BeanInfo targetBeanInfo = getTargetBeanInfo();
1638         if (targetBeanInfo != null) {
1639             return targetBeanInfo.getIcon(iconKind);
1640         }
1641         return super.getIcon(iconKind);
1642     }
1643 
1644     private BeanInfo getTargetBeanInfo() {
1645         if (this.targetBeanInfoRef == null) {
1646             return null;
1647         }
1648         BeanInfo targetBeanInfo = this.targetBeanInfoRef.get();
1649         if (targetBeanInfo == null) {
1650             targetBeanInfo = ThreadGroupContext.getContext().getBeanInfoFinder()
1651                     .find(this.beanDescriptor.getBeanClass());
1652             if (targetBeanInfo != null) {
1653                 this.targetBeanInfoRef = new SoftReference<>(targetBeanInfo);
1654             }
1655         }
1656         return targetBeanInfo;
1657     }
1658 }