1 /*
   2  * Copyright (c) 2013, 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 package java.lang.reflect;
  26 
  27 import java.lang.annotation.*;
  28 import java.util.HashMap;
  29 import java.util.Map;
  30 import java.util.Objects;
  31 import sun.reflect.annotation.AnnotationSupport;
  32 
  33 /**
  34  * Information about method parameters.
  35  *
  36  * A {@code Parameter} provides information about method parameters,
  37  * including its name and modifiers.  It also provides an alternate
  38  * means of obtaining attributes for the parameter.
  39  *
  40  * @since 1.8
  41  */
  42 public final class Parameter implements AnnotatedElement {
  43 
  44     private final String name;
  45     private final int modifiers;
  46     private final Executable executable;
  47     private final int index;
  48 
  49     /**
  50      * Package-private constructor for {@code Parameter}.
  51      *
  52      * If method parameter data is present in the classfile, then the
  53      * JVM creates {@code Parameter} objects directly.  If it is
  54      * absent, however, then {@code Executable} uses this constructor
  55      * to synthesize them.
  56      *
  57      * @param name The name of the parameter.
  58      * @param modifiers The modifier flags for the parameter.
  59      * @param executable The executable which defines this parameter.
  60      * @param index The index of the parameter.
  61      */
  62     Parameter(String name,
  63               int modifiers,
  64               Executable executable,
  65               int index) {
  66         this.name = name;
  67         this.modifiers = modifiers;
  68         this.executable = executable;
  69         this.index = index;
  70     }
  71 
  72     /**
  73      * Compares based on the executable and the index.
  74      *
  75      * @param obj The object to compare.
  76      * @return Whether or not this is equal to the argument.
  77      */
  78     public boolean equals(Object obj) {
  79         if(obj instanceof Parameter) {
  80             Parameter other = (Parameter)obj;
  81             return (other.executable.equals(executable) &&
  82                     other.index == index);
  83         }
  84         return false;
  85     }
  86 
  87     /**
  88      * Returns a hash code based on the executable's hash code and the
  89      * index.
  90      *
  91      * @return A hash code based on the executable's hash code.
  92      */
  93     public int hashCode() {
  94         return executable.hashCode() ^ index;
  95     }
  96 
  97     /**
  98      * Returns a string describing this parameter.  The format is the
  99      * modifiers for the parameter, if any, in canonical order as
 100      * recommended by <cite>The Java&trade; Language
 101      * Specification</cite>, followed by the fully- qualified type of
 102      * the parameter (excluding the last [] if the parameter is
 103      * variable arity), followed by "..." if the parameter is variable
 104      * arity, followed by a space, followed by the name of the
 105      * parameter.
 106      *
 107      * @return A string representation of the parameter and associated
 108      * information.
 109      */
 110     public String toString() {
 111         final StringBuilder sb = new StringBuilder();
 112         final Type type = getParameterizedType();
 113         final String typename = type.getTypeName();
 114 
 115         sb.append(Modifier.toString(getModifiers()));
 116 
 117         if(0 != modifiers)
 118             sb.append(' ');
 119 
 120         if(isVarArgs())
 121             sb.append(typename.replaceFirst("\\[\\]$", "..."));
 122         else
 123             sb.append(typename);
 124 
 125         sb.append(' ');
 126         sb.append(getName());
 127 
 128         return sb.toString();
 129     }
 130 
 131     /**
 132      * Return the {@code Executable} which declares this parameter.
 133      *
 134      * @return The {@code Executable} declaring this parameter.
 135      */
 136     public Executable getDeclaringExecutable() {
 137         return executable;
 138     }
 139 
 140     /**
 141      * Get the modifier flags for this the parameter represented by
 142      * this {@code Parameter} object.
 143      *
 144      * @return The modifier flags for this parameter.
 145      */
 146     public int getModifiers() {
 147         return modifiers;
 148     }
 149 
 150     /**
 151      * Returns the name of the parameter.  If the parameter's name is
 152      * defined in a class file, then that name will be returned by
 153      * this method.  Otherwise, this method will synthesize a name of
 154      * the form argN, where N is the index of the parameter..
 155      */
 156     public String getName() {
 157         // As per the spec, if a parameter has no name, return argX,
 158         // where x is the index.
 159         //
 160         // Note: spec updates now outlaw empty strings as parameter
 161         // names.  The .equals("") is for compatibility with current
 162         // JVM behavior.  It may be removed at some point.
 163         if(name == null || name.equals(""))
 164             return "arg" + index;
 165         else
 166             return name;
 167     }
 168 
 169     /**
 170      * Returns a {@code Type} object that identifies the parameterized
 171      * type for the parameter represented by this {@code Parameter}
 172      * object.
 173      *
 174      * @return a {@code Type} object identifying the parameterized
 175      * type of the parameter represented by this object
 176      */
 177     public Type getParameterizedType() {
 178         Type tmp = parameterTypeCache;
 179         if (null == tmp) {
 180             tmp = executable.getGenericParameterTypes()[index];
 181             parameterTypeCache = tmp;
 182         }
 183 
 184         return tmp;
 185     }
 186 
 187     private transient volatile Type parameterTypeCache = null;
 188 
 189     /**
 190      * Returns a {@code Class} object that identifies the
 191      * declared type for the parameter represented by this
 192      * {@code Parameter} object.
 193      *
 194      * @return a {@code Class} object identifying the declared
 195      * type of the parameter represented by this object
 196      */
 197     public Class<?> getType() {
 198         Class<?> tmp = parameterClassCache;
 199         if (null == tmp) {
 200             tmp = executable.getParameterTypes()[index];
 201             parameterClassCache = tmp;
 202         }
 203         return tmp;
 204     }
 205 
 206     private transient volatile Class<?> parameterClassCache = null;
 207 
 208     /**
 209      * Returns {@code true} if this parameter is implicitly declared
 210      * in source code; returns {@code false} otherwise.
 211      *
 212      * @return true if and only if this parameter is implicitly
 213      * declared as defined by <cite>The Java&trade; Language
 214      * Specification</cite>.
 215      */
 216     public boolean isImplicit() {
 217         return Modifier.isMandated(getModifiers());
 218     }
 219 
 220     /**
 221      * Returns {@code true} if this parameter is neither implicitly
 222      * nor explicitly declared in source code; returns {@code false}
 223      * otherwise.
 224      *
 225      * @jls 13.1 The Form of a Binary
 226      * @return true if and only if this parameter is a synthetic
 227      * construct as defined by
 228      * <cite>The Java&trade; Language Specification</cite>.
 229      */
 230     public boolean isSynthetic() {
 231         return Modifier.isSynthetic(getModifiers());
 232     }
 233 
 234     /**
 235      * Returns {@code true} if this parameter represents a variable
 236      * argument list; returns {@code false} otherwise.
 237      *
 238      * @return {@code true} if an only if this parameter represents a
 239      * variable argument list.
 240      */
 241     public boolean isVarArgs() {
 242         return executable.isVarArgs() &&
 243             index == executable.getParameterCount() - 1;
 244     }
 245 
 246 
 247     /**
 248      * {@inheritDoc}
 249      * @throws NullPointerException {@inheritDoc}
 250      */
 251     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 252         Objects.requireNonNull(annotationClass);
 253         return annotationClass.cast(declaredAnnotations().get(annotationClass));
 254     }
 255 
 256     /**
 257      * {@inheritDoc}
 258      * @throws NullPointerException {@inheritDoc}
 259      */
 260     @Override
 261     public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
 262         Objects.requireNonNull(annotationClass);
 263 
 264         return AnnotationSupport.getMultipleAnnotations(declaredAnnotations(), annotationClass);
 265     }
 266 
 267     /**
 268      * {@inheritDoc}
 269      */
 270     public Annotation[] getDeclaredAnnotations() {
 271         return executable.getParameterAnnotations()[index];
 272     }
 273 
 274     /**
 275      * @throws NullPointerException {@inheritDoc}
 276      */
 277     public <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
 278         // Only annotations on classes are inherited, for all other
 279         // objects getDeclaredAnnotation is the same as
 280         // getAnnotation.
 281         return getAnnotation(annotationClass);
 282     }
 283 
 284     /**
 285      * @throws NullPointerException {@inheritDoc}
 286      */
 287     @Override
 288     public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
 289         // Only annotations on classes are inherited, for all other
 290         // objects getDeclaredAnnotations is the same as
 291         // getAnnotations.
 292         return getAnnotationsByType(annotationClass);
 293     }
 294 
 295     /**
 296      * {@inheritDoc}
 297      */
 298     public Annotation[] getAnnotations() {
 299         return getDeclaredAnnotations();
 300     }
 301 
 302     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
 303 
 304     private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
 305         if(null == declaredAnnotations) {
 306             declaredAnnotations =
 307                 new HashMap<Class<? extends Annotation>, Annotation>();
 308             Annotation[] ann = getDeclaredAnnotations();
 309             for(int i = 0; i < ann.length; i++)
 310                 declaredAnnotations.put(ann[i].annotationType(), ann[i]);
 311         }
 312         return declaredAnnotations;
 313    }
 314 
 315 }