emul/src/main/java/java/lang/reflect/Method.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 04 Dec 2012 15:32:18 +0100
branchreflection
changeset 262 683719ffcfe7
parent 260 1d03cb35fbda
child 264 ed0c92c81ea4
permissions -rw-r--r--
Can execute a (parameterless) method via reflection
     1 /*
     2  * Copyright (c) 1996, 2006, 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.lang.reflect;
    27 
    28 import java.lang.annotation.Annotation;
    29 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    30 
    31 /**
    32  * A {@code Method} provides information about, and access to, a single method
    33  * on a class or interface.  The reflected method may be a class method
    34  * or an instance method (including an abstract method).
    35  *
    36  * <p>A {@code Method} permits widening conversions to occur when matching the
    37  * actual parameters to invoke with the underlying method's formal
    38  * parameters, but it throws an {@code IllegalArgumentException} if a
    39  * narrowing conversion would occur.
    40  *
    41  * @see Member
    42  * @see java.lang.Class
    43  * @see java.lang.Class#getMethods()
    44  * @see java.lang.Class#getMethod(String, Class[])
    45  * @see java.lang.Class#getDeclaredMethods()
    46  * @see java.lang.Class#getDeclaredMethod(String, Class[])
    47  *
    48  * @author Kenneth Russell
    49  * @author Nakul Saraiya
    50  */
    51 public final
    52     class Method extends AccessibleObject implements GenericDeclaration,
    53                                                      Member {
    54     private final Class<?> clazz;
    55     private final String name;
    56     private final Object data;
    57     private int modifiers;
    58 
    59    // Generics infrastructure
    60 
    61     private String getGenericSignature() {return null;}
    62 
    63     /**
    64      * Package-private constructor used by ReflectAccess to enable
    65      * instantiation of these objects in Java code from the java.lang
    66      * package via sun.reflect.LangReflectAccess.
    67      */
    68     Method(Class<?> declaringClass,
    69            String name, Object data)
    70     {
    71         this.clazz = declaringClass;
    72         this.name = name;
    73         this.data = data;
    74     }
    75 
    76     /**
    77      * Package-private routine (exposed to java.lang.Class via
    78      * ReflectAccess) which returns a copy of this Method. The copy's
    79      * "root" field points to this Method.
    80      */
    81     Method copy() {
    82         return this;
    83     }
    84 
    85     /**
    86      * Returns the {@code Class} object representing the class or interface
    87      * that declares the method represented by this {@code Method} object.
    88      */
    89     public Class<?> getDeclaringClass() {
    90         return clazz;
    91     }
    92 
    93     /**
    94      * Returns the name of the method represented by this {@code Method}
    95      * object, as a {@code String}.
    96      */
    97     public String getName() {
    98         return name;
    99     }
   100 
   101     /**
   102      * Returns the Java language modifiers for the method represented
   103      * by this {@code Method} object, as an integer. The {@code Modifier} class should
   104      * be used to decode the modifiers.
   105      *
   106      * @see Modifier
   107      */
   108     public int getModifiers() {
   109         return modifiers;
   110     }
   111 
   112     /**
   113      * Returns an array of {@code TypeVariable} objects that represent the
   114      * type variables declared by the generic declaration represented by this
   115      * {@code GenericDeclaration} object, in declaration order.  Returns an
   116      * array of length 0 if the underlying generic declaration declares no type
   117      * variables.
   118      *
   119      * @return an array of {@code TypeVariable} objects that represent
   120      *     the type variables declared by this generic declaration
   121      * @throws GenericSignatureFormatError if the generic
   122      *     signature of this generic declaration does not conform to
   123      *     the format specified in
   124      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   125      * @since 1.5
   126      */
   127     public TypeVariable<Method>[] getTypeParameters() {
   128         throw new UnsupportedOperationException();
   129     }
   130 
   131     /**
   132      * Returns a {@code Class} object that represents the formal return type
   133      * of the method represented by this {@code Method} object.
   134      *
   135      * @return the return type for the method this object represents
   136      */
   137     public Class<?> getReturnType() {
   138         throw new UnsupportedOperationException();
   139     }
   140 
   141     /**
   142      * Returns a {@code Type} object that represents the formal return
   143      * type of the method represented by this {@code Method} object.
   144      *
   145      * <p>If the return type is a parameterized type,
   146      * the {@code Type} object returned must accurately reflect
   147      * the actual type parameters used in the source code.
   148      *
   149      * <p>If the return type is a type variable or a parameterized type, it
   150      * is created. Otherwise, it is resolved.
   151      *
   152      * @return  a {@code Type} object that represents the formal return
   153      *     type of the underlying  method
   154      * @throws GenericSignatureFormatError
   155      *     if the generic method signature does not conform to the format
   156      *     specified in
   157      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   158      * @throws TypeNotPresentException if the underlying method's
   159      *     return type refers to a non-existent type declaration
   160      * @throws MalformedParameterizedTypeException if the
   161      *     underlying method's return typed refers to a parameterized
   162      *     type that cannot be instantiated for any reason
   163      * @since 1.5
   164      */
   165     public Type getGenericReturnType() {
   166         throw new UnsupportedOperationException();
   167     }
   168 
   169 
   170     /**
   171      * Returns an array of {@code Class} objects that represent the formal
   172      * parameter types, in declaration order, of the method
   173      * represented by this {@code Method} object.  Returns an array of length
   174      * 0 if the underlying method takes no parameters.
   175      *
   176      * @return the parameter types for the method this object
   177      * represents
   178      */
   179     public Class<?>[] getParameterTypes() {
   180         throw new UnsupportedOperationException();
   181         //return (Class<?>[]) parameterTypes.clone();
   182     }
   183 
   184     /**
   185      * Returns an array of {@code Type} objects that represent the formal
   186      * parameter types, in declaration order, of the method represented by
   187      * this {@code Method} object. Returns an array of length 0 if the
   188      * underlying method takes no parameters.
   189      *
   190      * <p>If a formal parameter type is a parameterized type,
   191      * the {@code Type} object returned for it must accurately reflect
   192      * the actual type parameters used in the source code.
   193      *
   194      * <p>If a formal parameter type is a type variable or a parameterized
   195      * type, it is created. Otherwise, it is resolved.
   196      *
   197      * @return an array of Types that represent the formal
   198      *     parameter types of the underlying method, in declaration order
   199      * @throws GenericSignatureFormatError
   200      *     if the generic method signature does not conform to the format
   201      *     specified in
   202      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   203      * @throws TypeNotPresentException if any of the parameter
   204      *     types of the underlying method refers to a non-existent type
   205      *     declaration
   206      * @throws MalformedParameterizedTypeException if any of
   207      *     the underlying method's parameter types refer to a parameterized
   208      *     type that cannot be instantiated for any reason
   209      * @since 1.5
   210      */
   211     public Type[] getGenericParameterTypes() {
   212         throw new UnsupportedOperationException();
   213     }
   214 
   215 
   216     /**
   217      * Returns an array of {@code Class} objects that represent
   218      * the types of the exceptions declared to be thrown
   219      * by the underlying method
   220      * represented by this {@code Method} object.  Returns an array of length
   221      * 0 if the method declares no exceptions in its {@code throws} clause.
   222      *
   223      * @return the exception types declared as being thrown by the
   224      * method this object represents
   225      */
   226     public Class<?>[] getExceptionTypes() {
   227         throw new UnsupportedOperationException();
   228         //return (Class<?>[]) exceptionTypes.clone();
   229     }
   230 
   231     /**
   232      * Returns an array of {@code Type} objects that represent the
   233      * exceptions declared to be thrown by this {@code Method} object.
   234      * Returns an array of length 0 if the underlying method declares
   235      * no exceptions in its {@code throws} clause.
   236      *
   237      * <p>If an exception type is a type variable or a parameterized
   238      * type, it is created. Otherwise, it is resolved.
   239      *
   240      * @return an array of Types that represent the exception types
   241      *     thrown by the underlying method
   242      * @throws GenericSignatureFormatError
   243      *     if the generic method signature does not conform to the format
   244      *     specified in
   245      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   246      * @throws TypeNotPresentException if the underlying method's
   247      *     {@code throws} clause refers to a non-existent type declaration
   248      * @throws MalformedParameterizedTypeException if
   249      *     the underlying method's {@code throws} clause refers to a
   250      *     parameterized type that cannot be instantiated for any reason
   251      * @since 1.5
   252      */
   253       public Type[] getGenericExceptionTypes() {
   254         throw new UnsupportedOperationException();
   255       }
   256 
   257     /**
   258      * Compares this {@code Method} against the specified object.  Returns
   259      * true if the objects are the same.  Two {@code Methods} are the same if
   260      * they were declared by the same class and have the same name
   261      * and formal parameter types and return type.
   262      */
   263     public boolean equals(Object obj) {
   264         if (obj != null && obj instanceof Method) {
   265             Method other = (Method)obj;
   266             return data == other.data;
   267         }
   268         return false;
   269     }
   270 
   271     /**
   272      * Returns a hashcode for this {@code Method}.  The hashcode is computed
   273      * as the exclusive-or of the hashcodes for the underlying
   274      * method's declaring class name and the method's name.
   275      */
   276     public int hashCode() {
   277         return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
   278     }
   279 
   280     /**
   281      * Returns a string describing this {@code Method}.  The string is
   282      * formatted as the method access modifiers, if any, followed by
   283      * the method return type, followed by a space, followed by the
   284      * class declaring the method, followed by a period, followed by
   285      * the method name, followed by a parenthesized, comma-separated
   286      * list of the method's formal parameter types. If the method
   287      * throws checked exceptions, the parameter list is followed by a
   288      * space, followed by the word throws followed by a
   289      * comma-separated list of the thrown exception types.
   290      * For example:
   291      * <pre>
   292      *    public boolean java.lang.Object.equals(java.lang.Object)
   293      * </pre>
   294      *
   295      * <p>The access modifiers are placed in canonical order as
   296      * specified by "The Java Language Specification".  This is
   297      * {@code public}, {@code protected} or {@code private} first,
   298      * and then other modifiers in the following order:
   299      * {@code abstract}, {@code static}, {@code final},
   300      * {@code synchronized}, {@code native}, {@code strictfp}.
   301      */
   302     public String toString() {
   303         try {
   304             StringBuilder sb = new StringBuilder();
   305             int mod = getModifiers() & Modifier.methodModifiers();
   306             if (mod != 0) {
   307                 sb.append(Modifier.toString(mod)).append(' ');
   308             }
   309             sb.append(Field.getTypeName(getReturnType())).append(' ');
   310             sb.append(Field.getTypeName(getDeclaringClass())).append('.');
   311             sb.append(getName()).append('(');
   312             /*
   313             Class<?>[] params = parameterTypes; // avoid clone
   314             for (int j = 0; j < params.length; j++) {
   315                 sb.append(Field.getTypeName(params[j]));
   316                 if (j < (params.length - 1))
   317                     sb.append(',');
   318             }
   319             sb.append(')');
   320             Class<?>[] exceptions = exceptionTypes; // avoid clone
   321             if (exceptions.length > 0) {
   322                 sb.append(" throws ");
   323                 for (int k = 0; k < exceptions.length; k++) {
   324                     sb.append(exceptions[k].getName());
   325                     if (k < (exceptions.length - 1))
   326                         sb.append(',');
   327                 }
   328             }
   329             */
   330             return sb.toString();
   331         } catch (Exception e) {
   332             return "<" + e + ">";
   333         }
   334     }
   335 
   336     /**
   337      * Returns a string describing this {@code Method}, including
   338      * type parameters.  The string is formatted as the method access
   339      * modifiers, if any, followed by an angle-bracketed
   340      * comma-separated list of the method's type parameters, if any,
   341      * followed by the method's generic return type, followed by a
   342      * space, followed by the class declaring the method, followed by
   343      * a period, followed by the method name, followed by a
   344      * parenthesized, comma-separated list of the method's generic
   345      * formal parameter types.
   346      *
   347      * If this method was declared to take a variable number of
   348      * arguments, instead of denoting the last parameter as
   349      * "<tt><i>Type</i>[]</tt>", it is denoted as
   350      * "<tt><i>Type</i>...</tt>".
   351      *
   352      * A space is used to separate access modifiers from one another
   353      * and from the type parameters or return type.  If there are no
   354      * type parameters, the type parameter list is elided; if the type
   355      * parameter list is present, a space separates the list from the
   356      * class name.  If the method is declared to throw exceptions, the
   357      * parameter list is followed by a space, followed by the word
   358      * throws followed by a comma-separated list of the generic thrown
   359      * exception types.  If there are no type parameters, the type
   360      * parameter list is elided.
   361      *
   362      * <p>The access modifiers are placed in canonical order as
   363      * specified by "The Java Language Specification".  This is
   364      * {@code public}, {@code protected} or {@code private} first,
   365      * and then other modifiers in the following order:
   366      * {@code abstract}, {@code static}, {@code final},
   367      * {@code synchronized}, {@code native}, {@code strictfp}.
   368      *
   369      * @return a string describing this {@code Method},
   370      * include type parameters
   371      *
   372      * @since 1.5
   373      */
   374     public String toGenericString() {
   375         try {
   376             StringBuilder sb = new StringBuilder();
   377             int mod = getModifiers() & Modifier.methodModifiers();
   378             if (mod != 0) {
   379                 sb.append(Modifier.toString(mod)).append(' ');
   380             }
   381             TypeVariable<?>[] typeparms = getTypeParameters();
   382             if (typeparms.length > 0) {
   383                 boolean first = true;
   384                 sb.append('<');
   385                 for(TypeVariable<?> typeparm: typeparms) {
   386                     if (!first)
   387                         sb.append(',');
   388                     // Class objects can't occur here; no need to test
   389                     // and call Class.getName().
   390                     sb.append(typeparm.toString());
   391                     first = false;
   392                 }
   393                 sb.append("> ");
   394             }
   395 
   396             Type genRetType = getGenericReturnType();
   397             sb.append( ((genRetType instanceof Class<?>)?
   398                         Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
   399                     .append(' ');
   400 
   401             sb.append(Field.getTypeName(getDeclaringClass())).append('.');
   402             sb.append(getName()).append('(');
   403             Type[] params = getGenericParameterTypes();
   404             for (int j = 0; j < params.length; j++) {
   405                 String param = (params[j] instanceof Class)?
   406                     Field.getTypeName((Class)params[j]):
   407                     (params[j].toString());
   408                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
   409                     param = param.replaceFirst("\\[\\]$", "...");
   410                 sb.append(param);
   411                 if (j < (params.length - 1))
   412                     sb.append(',');
   413             }
   414             sb.append(')');
   415             Type[] exceptions = getGenericExceptionTypes();
   416             if (exceptions.length > 0) {
   417                 sb.append(" throws ");
   418                 for (int k = 0; k < exceptions.length; k++) {
   419                     sb.append((exceptions[k] instanceof Class)?
   420                               ((Class)exceptions[k]).getName():
   421                               exceptions[k].toString());
   422                     if (k < (exceptions.length - 1))
   423                         sb.append(',');
   424                 }
   425             }
   426             return sb.toString();
   427         } catch (Exception e) {
   428             return "<" + e + ">";
   429         }
   430     }
   431 
   432     /**
   433      * Invokes the underlying method represented by this {@code Method}
   434      * object, on the specified object with the specified parameters.
   435      * Individual parameters are automatically unwrapped to match
   436      * primitive formal parameters, and both primitive and reference
   437      * parameters are subject to method invocation conversions as
   438      * necessary.
   439      *
   440      * <p>If the underlying method is static, then the specified {@code obj}
   441      * argument is ignored. It may be null.
   442      *
   443      * <p>If the number of formal parameters required by the underlying method is
   444      * 0, the supplied {@code args} array may be of length 0 or null.
   445      *
   446      * <p>If the underlying method is an instance method, it is invoked
   447      * using dynamic method lookup as documented in The Java Language
   448      * Specification, Second Edition, section 15.12.4.4; in particular,
   449      * overriding based on the runtime type of the target object will occur.
   450      *
   451      * <p>If the underlying method is static, the class that declared
   452      * the method is initialized if it has not already been initialized.
   453      *
   454      * <p>If the method completes normally, the value it returns is
   455      * returned to the caller of invoke; if the value has a primitive
   456      * type, it is first appropriately wrapped in an object. However,
   457      * if the value has the type of an array of a primitive type, the
   458      * elements of the array are <i>not</i> wrapped in objects; in
   459      * other words, an array of primitive type is returned.  If the
   460      * underlying method return type is void, the invocation returns
   461      * null.
   462      *
   463      * @param obj  the object the underlying method is invoked from
   464      * @param args the arguments used for the method call
   465      * @return the result of dispatching the method represented by
   466      * this object on {@code obj} with parameters
   467      * {@code args}
   468      *
   469      * @exception IllegalAccessException    if this {@code Method} object
   470      *              is enforcing Java language access control and the underlying
   471      *              method is inaccessible.
   472      * @exception IllegalArgumentException  if the method is an
   473      *              instance method and the specified object argument
   474      *              is not an instance of the class or interface
   475      *              declaring the underlying method (or of a subclass
   476      *              or implementor thereof); if the number of actual
   477      *              and formal parameters differ; if an unwrapping
   478      *              conversion for primitive arguments fails; or if,
   479      *              after possible unwrapping, a parameter value
   480      *              cannot be converted to the corresponding formal
   481      *              parameter type by a method invocation conversion.
   482      * @exception InvocationTargetException if the underlying method
   483      *              throws an exception.
   484      * @exception NullPointerException      if the specified object is null
   485      *              and the method is an instance method.
   486      * @exception ExceptionInInitializerError if the initialization
   487      * provoked by this method fails.
   488      */
   489     @JavaScriptBody(args = { "method", "self", "args" }, body =
   490           "if (args.length > 0) throw 'unsupported now';"
   491         + "return method.fld_data(self);"
   492     )
   493     public Object invoke(Object obj, Object... args)
   494         throws IllegalAccessException, IllegalArgumentException,
   495            InvocationTargetException
   496     {
   497         throw new UnsupportedOperationException();
   498     }
   499 
   500     /**
   501      * Returns {@code true} if this method is a bridge
   502      * method; returns {@code false} otherwise.
   503      *
   504      * @return true if and only if this method is a bridge
   505      * method as defined by the Java Language Specification.
   506      * @since 1.5
   507      */
   508     public boolean isBridge() {
   509         return (getModifiers() & Modifier.BRIDGE) != 0;
   510     }
   511 
   512     /**
   513      * Returns {@code true} if this method was declared to take
   514      * a variable number of arguments; returns {@code false}
   515      * otherwise.
   516      *
   517      * @return {@code true} if an only if this method was declared to
   518      * take a variable number of arguments.
   519      * @since 1.5
   520      */
   521     public boolean isVarArgs() {
   522         return (getModifiers() & Modifier.VARARGS) != 0;
   523     }
   524 
   525     /**
   526      * Returns {@code true} if this method is a synthetic
   527      * method; returns {@code false} otherwise.
   528      *
   529      * @return true if and only if this method is a synthetic
   530      * method as defined by the Java Language Specification.
   531      * @since 1.5
   532      */
   533     public boolean isSynthetic() {
   534         return Modifier.isSynthetic(getModifiers());
   535     }
   536 
   537     /**
   538      * @throws NullPointerException {@inheritDoc}
   539      * @since 1.5
   540      */
   541     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
   542         if (annotationClass == null)
   543             throw new NullPointerException();
   544 
   545         throw new UnsupportedOperationException();
   546     }
   547 
   548     /**
   549      * @since 1.5
   550      */
   551     public Annotation[] getDeclaredAnnotations()  {
   552         throw new UnsupportedOperationException();
   553     }
   554 
   555     /**
   556      * Returns the default value for the annotation member represented by
   557      * this {@code Method} instance.  If the member is of a primitive type,
   558      * an instance of the corresponding wrapper type is returned. Returns
   559      * null if no default is associated with the member, or if the method
   560      * instance does not represent a declared member of an annotation type.
   561      *
   562      * @return the default value for the annotation member represented
   563      *     by this {@code Method} instance.
   564      * @throws TypeNotPresentException if the annotation is of type
   565      *     {@link Class} and no definition can be found for the
   566      *     default class value.
   567      * @since  1.5
   568      */
   569     public Object getDefaultValue() {
   570         throw new UnsupportedOperationException();
   571     }
   572 
   573     /**
   574      * Returns an array of arrays that represent the annotations on the formal
   575      * parameters, in declaration order, of the method represented by
   576      * this {@code Method} object. (Returns an array of length zero if the
   577      * underlying method is parameterless.  If the method has one or more
   578      * parameters, a nested array of length zero is returned for each parameter
   579      * with no annotations.) The annotation objects contained in the returned
   580      * arrays are serializable.  The caller of this method is free to modify
   581      * the returned arrays; it will have no effect on the arrays returned to
   582      * other callers.
   583      *
   584      * @return an array of arrays that represent the annotations on the formal
   585      *    parameters, in declaration order, of the method represented by this
   586      *    Method object
   587      * @since 1.5
   588      */
   589     public Annotation[][] getParameterAnnotations() {
   590         throw new UnsupportedOperationException();
   591     }
   592     
   593     //
   594     // bck2brwsr implementation
   595     //
   596 
   597     @JavaScriptBody(args = { "clazz", "name", "params" },
   598         body = "if (params.length > 0) return null;\n"
   599         + "var c = clazz.cnstr.prototype;"
   600         + "var prefix = name + '__';\n"
   601         + "for (m in c) {\n"
   602         + "  if (m.indexOf(prefix) === 0) {"
   603         + "     return c[m];\n"
   604         + "  }"
   605         + "}\n"
   606         + "return null;"
   607     )
   608     private static native Object findMethodData(
   609         Class<?> clazz, String name, Class<?>... parameterTypes
   610     );
   611     
   612     // XXX should not be public
   613     public static Method findMethod(
   614         Class<?> clazz, String name, Class<?>... parameterTypes
   615     ) {
   616         Object data = findMethodData(clazz, name, parameterTypes);
   617         if (data == null) {
   618             return null;
   619         }
   620         return new Method(clazz, name, data);
   621     }
   622 }