rt/emul/mini/src/main/java/java/lang/reflect/Method.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 20 Mar 2016 19:37:07 +0100
changeset 1903 0267fb5bc8d5
parent 1899 d729cfa77fa7
permissions -rw-r--r--
Return null if there is not the requested annotation on a method
     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 java.util.Enumeration;
    30 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    31 import org.apidesign.bck2brwsr.emul.reflect.AnnotationImpl;
    32 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
    33 
    34 /**
    35  * A {@code Method} provides information about, and access to, a single method
    36  * on a class or interface.  The reflected method may be a class method
    37  * or an instance method (including an abstract method).
    38  *
    39  * <p>A {@code Method} permits widening conversions to occur when matching the
    40  * actual parameters to invoke with the underlying method's formal
    41  * parameters, but it throws an {@code IllegalArgumentException} if a
    42  * narrowing conversion would occur.
    43  *
    44  * @see Member
    45  * @see java.lang.Class
    46  * @see java.lang.Class#getMethods()
    47  * @see java.lang.Class#getMethod(String, Class[])
    48  * @see java.lang.Class#getDeclaredMethods()
    49  * @see java.lang.Class#getDeclaredMethod(String, Class[])
    50  *
    51  * @author Kenneth Russell
    52  * @author Nakul Saraiya
    53  */
    54 public final
    55     class Method extends AccessibleObject implements GenericDeclaration,
    56                                                      Member {
    57     private final Class<?> clazz;
    58     private final String name;
    59     private final Object data;
    60     private final String sig;
    61 
    62    // Generics infrastructure
    63 
    64     private String getGenericSignature() {return null;}
    65 
    66     /**
    67      * Package-private constructor used by ReflectAccess to enable
    68      * instantiation of these objects in Java code from the java.lang
    69      * package via sun.reflect.LangReflectAccess.
    70      */
    71     Method(Class<?> declaringClass, String name, Object data, String sig)
    72     {
    73         this.clazz = declaringClass;
    74         this.name = name;
    75         this.data = data;
    76         this.sig = sig;
    77     }
    78 
    79     /**
    80      * Package-private routine (exposed to java.lang.Class via
    81      * ReflectAccess) which returns a copy of this Method. The copy's
    82      * "root" field points to this Method.
    83      */
    84     Method copy() {
    85         return this;
    86     }
    87 
    88     /**
    89      * Returns the {@code Class} object representing the class or interface
    90      * that declares the method represented by this {@code Method} object.
    91      */
    92     public Class<?> getDeclaringClass() {
    93         return clazz;
    94     }
    95 
    96     /**
    97      * Returns the name of the method represented by this {@code Method}
    98      * object, as a {@code String}.
    99      */
   100     public String getName() {
   101         return name;
   102     }
   103 
   104     /**
   105      * Returns the Java language modifiers for the method represented
   106      * by this {@code Method} object, as an integer. The {@code Modifier} class should
   107      * be used to decode the modifiers.
   108      *
   109      * @see Modifier
   110      */
   111     public int getModifiers() {
   112         return getAccess(data);
   113     }
   114     
   115     @JavaScriptBody(args = "self", body = "return self.access;")
   116     static native int getAccess(Object self);
   117     
   118     /**
   119      * Returns an array of {@code TypeVariable} objects that represent the
   120      * type variables declared by the generic declaration represented by this
   121      * {@code GenericDeclaration} object, in declaration order.  Returns an
   122      * array of length 0 if the underlying generic declaration declares no type
   123      * variables.
   124      *
   125      * @return an array of {@code TypeVariable} objects that represent
   126      *     the type variables declared by this generic declaration
   127      * @throws GenericSignatureFormatError if the generic
   128      *     signature of this generic declaration does not conform to
   129      *     the format specified in
   130      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   131      * @since 1.5
   132      */
   133     public TypeVariable<Method>[] getTypeParameters() {
   134         throw new UnsupportedOperationException();
   135     }
   136 
   137     /**
   138      * Returns a {@code Class} object that represents the formal return type
   139      * of the method represented by this {@code Method} object.
   140      *
   141      * @return the return type for the method this object represents
   142      */
   143     public Class<?> getReturnType() {
   144         return MethodImpl.signatureParser(sig).nextElement();
   145     }
   146 
   147     /**
   148      * Returns a {@code Type} object that represents the formal return
   149      * type of the method represented by this {@code Method} object.
   150      *
   151      * <p>If the return type is a parameterized type,
   152      * the {@code Type} object returned must accurately reflect
   153      * the actual type parameters used in the source code.
   154      *
   155      * <p>If the return type is a type variable or a parameterized type, it
   156      * is created. Otherwise, it is resolved.
   157      *
   158      * @return  a {@code Type} object that represents the formal return
   159      *     type of the underlying  method
   160      * @throws GenericSignatureFormatError
   161      *     if the generic method signature does not conform to the format
   162      *     specified in
   163      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   164      * @throws TypeNotPresentException if the underlying method's
   165      *     return type refers to a non-existent type declaration
   166      * @throws MalformedParameterizedTypeException if the
   167      *     underlying method's return typed refers to a parameterized
   168      *     type that cannot be instantiated for any reason
   169      * @since 1.5
   170      */
   171     public Type getGenericReturnType() {
   172         throw new UnsupportedOperationException();
   173     }
   174 
   175 
   176     /**
   177      * Returns an array of {@code Class} objects that represent the formal
   178      * parameter types, in declaration order, of the method
   179      * represented by this {@code Method} object.  Returns an array of length
   180      * 0 if the underlying method takes no parameters.
   181      *
   182      * @return the parameter types for the method this object
   183      * represents
   184      */
   185     public Class<?>[] getParameterTypes() {
   186         return getParameterTypes(sig);
   187     }
   188     
   189     static Class<?>[] getParameterTypes(String sig) {
   190         Class[] arr = new Class[MethodImpl.signatureElements(sig) - 1];
   191         Enumeration<Class> en = MethodImpl.signatureParser(sig);
   192         en.nextElement(); // return type
   193         for (int i = 0; i < arr.length; i++) {
   194             arr[i] = en.nextElement();
   195         }
   196         return arr;
   197     }
   198 
   199     /**
   200      * Returns an array of {@code Type} objects that represent the formal
   201      * parameter types, in declaration order, of the method represented by
   202      * this {@code Method} object. Returns an array of length 0 if the
   203      * underlying method takes no parameters.
   204      *
   205      * <p>If a formal parameter type is a parameterized type,
   206      * the {@code Type} object returned for it must accurately reflect
   207      * the actual type parameters used in the source code.
   208      *
   209      * <p>If a formal parameter type is a type variable or a parameterized
   210      * type, it is created. Otherwise, it is resolved.
   211      *
   212      * @return an array of Types that represent the formal
   213      *     parameter types of the underlying method, in declaration order
   214      * @throws GenericSignatureFormatError
   215      *     if the generic method signature does not conform to the format
   216      *     specified in
   217      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   218      * @throws TypeNotPresentException if any of the parameter
   219      *     types of the underlying method refers to a non-existent type
   220      *     declaration
   221      * @throws MalformedParameterizedTypeException if any of
   222      *     the underlying method's parameter types refer to a parameterized
   223      *     type that cannot be instantiated for any reason
   224      * @since 1.5
   225      */
   226     public Type[] getGenericParameterTypes() {
   227         throw new UnsupportedOperationException();
   228     }
   229 
   230 
   231     /**
   232      * Returns an array of {@code Class} objects that represent
   233      * the types of the exceptions declared to be thrown
   234      * by the underlying method
   235      * represented by this {@code Method} object.  Returns an array of length
   236      * 0 if the method declares no exceptions in its {@code throws} clause.
   237      *
   238      * @return the exception types declared as being thrown by the
   239      * method this object represents
   240      */
   241     public Class<?>[] getExceptionTypes() {
   242         return new Class[0];
   243     }
   244 
   245     /**
   246      * Returns an array of {@code Type} objects that represent the
   247      * exceptions declared to be thrown by this {@code Method} object.
   248      * Returns an array of length 0 if the underlying method declares
   249      * no exceptions in its {@code throws} clause.
   250      *
   251      * <p>If an exception type is a type variable or a parameterized
   252      * type, it is created. Otherwise, it is resolved.
   253      *
   254      * @return an array of Types that represent the exception types
   255      *     thrown by the underlying method
   256      * @throws GenericSignatureFormatError
   257      *     if the generic method signature does not conform to the format
   258      *     specified in
   259      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   260      * @throws TypeNotPresentException if the underlying method's
   261      *     {@code throws} clause refers to a non-existent type declaration
   262      * @throws MalformedParameterizedTypeException if
   263      *     the underlying method's {@code throws} clause refers to a
   264      *     parameterized type that cannot be instantiated for any reason
   265      * @since 1.5
   266      */
   267       public Type[] getGenericExceptionTypes() {
   268         throw new UnsupportedOperationException();
   269       }
   270 
   271     /**
   272      * Compares this {@code Method} against the specified object.  Returns
   273      * true if the objects are the same.  Two {@code Methods} are the same if
   274      * they were declared by the same class and have the same name
   275      * and formal parameter types and return type.
   276      */
   277     public boolean equals(Object obj) {
   278         if (obj != null && obj instanceof Method) {
   279             Method other = (Method)obj;
   280             return data == other.data;
   281         }
   282         return false;
   283     }
   284 
   285     /**
   286      * Returns a hashcode for this {@code Method}.  The hashcode is computed
   287      * as the exclusive-or of the hashcodes for the underlying
   288      * method's declaring class name and the method's name.
   289      */
   290     public int hashCode() {
   291         return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
   292     }
   293 
   294     /**
   295      * Returns a string describing this {@code Method}.  The string is
   296      * formatted as the method access modifiers, if any, followed by
   297      * the method return type, followed by a space, followed by the
   298      * class declaring the method, followed by a period, followed by
   299      * the method name, followed by a parenthesized, comma-separated
   300      * list of the method's formal parameter types. If the method
   301      * throws checked exceptions, the parameter list is followed by a
   302      * space, followed by the word throws followed by a
   303      * comma-separated list of the thrown exception types.
   304      * For example:
   305      * <pre>
   306      *    public boolean java.lang.Object.equals(java.lang.Object)
   307      * </pre>
   308      *
   309      * <p>The access modifiers are placed in canonical order as
   310      * specified by "The Java Language Specification".  This is
   311      * {@code public}, {@code protected} or {@code private} first,
   312      * and then other modifiers in the following order:
   313      * {@code abstract}, {@code static}, {@code final},
   314      * {@code synchronized}, {@code native}, {@code strictfp}.
   315      */
   316     public String toString() {
   317         try {
   318             StringBuilder sb = new StringBuilder();
   319             int mod = getModifiers() & Modifier.methodModifiers();
   320             if (mod != 0) {
   321                 sb.append(Modifier.toString(mod)).append(' ');
   322             }
   323             sb.append(Field.getTypeName(getReturnType())).append(' ');
   324             sb.append(Field.getTypeName(getDeclaringClass())).append('.');
   325             sb.append(getName()).append('(');
   326             Class<?>[] params = getParameterTypes(); // avoid clone
   327             for (int j = 0; j < params.length; j++) {
   328                 sb.append(Field.getTypeName(params[j]));
   329                 if (j < (params.length - 1))
   330                     sb.append(',');
   331             }
   332             sb.append(')');
   333             /*
   334             Class<?>[] exceptions = exceptionTypes; // avoid clone
   335             if (exceptions.length > 0) {
   336                 sb.append(" throws ");
   337                 for (int k = 0; k < exceptions.length; k++) {
   338                     sb.append(exceptions[k].getName());
   339                     if (k < (exceptions.length - 1))
   340                         sb.append(',');
   341                 }
   342             }
   343             */
   344             return sb.toString();
   345         } catch (Exception e) {
   346             return "<" + e + ">";
   347         }
   348     }
   349 
   350     /**
   351      * Returns a string describing this {@code Method}, including
   352      * type parameters.  The string is formatted as the method access
   353      * modifiers, if any, followed by an angle-bracketed
   354      * comma-separated list of the method's type parameters, if any,
   355      * followed by the method's generic return type, followed by a
   356      * space, followed by the class declaring the method, followed by
   357      * a period, followed by the method name, followed by a
   358      * parenthesized, comma-separated list of the method's generic
   359      * formal parameter types.
   360      *
   361      * If this method was declared to take a variable number of
   362      * arguments, instead of denoting the last parameter as
   363      * "<tt><i>Type</i>[]</tt>", it is denoted as
   364      * "<tt><i>Type</i>...</tt>".
   365      *
   366      * A space is used to separate access modifiers from one another
   367      * and from the type parameters or return type.  If there are no
   368      * type parameters, the type parameter list is elided; if the type
   369      * parameter list is present, a space separates the list from the
   370      * class name.  If the method is declared to throw exceptions, the
   371      * parameter list is followed by a space, followed by the word
   372      * throws followed by a comma-separated list of the generic thrown
   373      * exception types.  If there are no type parameters, the type
   374      * parameter list is elided.
   375      *
   376      * <p>The access modifiers are placed in canonical order as
   377      * specified by "The Java Language Specification".  This is
   378      * {@code public}, {@code protected} or {@code private} first,
   379      * and then other modifiers in the following order:
   380      * {@code abstract}, {@code static}, {@code final},
   381      * {@code synchronized}, {@code native}, {@code strictfp}.
   382      *
   383      * @return a string describing this {@code Method},
   384      * include type parameters
   385      *
   386      * @since 1.5
   387      */
   388     public String toGenericString() {
   389         try {
   390             StringBuilder sb = new StringBuilder();
   391             int mod = getModifiers() & Modifier.methodModifiers();
   392             if (mod != 0) {
   393                 sb.append(Modifier.toString(mod)).append(' ');
   394             }
   395             TypeVariable<?>[] typeparms = getTypeParameters();
   396             if (typeparms.length > 0) {
   397                 boolean first = true;
   398                 sb.append('<');
   399                 for(TypeVariable<?> typeparm: typeparms) {
   400                     if (!first)
   401                         sb.append(',');
   402                     // Class objects can't occur here; no need to test
   403                     // and call Class.getName().
   404                     sb.append(typeparm.toString());
   405                     first = false;
   406                 }
   407                 sb.append("> ");
   408             }
   409 
   410             Type genRetType = getGenericReturnType();
   411             sb.append( ((genRetType instanceof Class<?>)?
   412                         Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
   413                     .append(' ');
   414 
   415             sb.append(Field.getTypeName(getDeclaringClass())).append('.');
   416             sb.append(getName()).append('(');
   417             Type[] params = getGenericParameterTypes();
   418             for (int j = 0; j < params.length; j++) {
   419                 String param = (params[j] instanceof Class)?
   420                     Field.getTypeName((Class)params[j]):
   421                     (params[j].toString());
   422                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
   423                     param = param.replaceFirst("\\[\\]$", "...");
   424                 sb.append(param);
   425                 if (j < (params.length - 1))
   426                     sb.append(',');
   427             }
   428             sb.append(')');
   429             Type[] exceptions = getGenericExceptionTypes();
   430             if (exceptions.length > 0) {
   431                 sb.append(" throws ");
   432                 for (int k = 0; k < exceptions.length; k++) {
   433                     sb.append((exceptions[k] instanceof Class)?
   434                               ((Class)exceptions[k]).getName():
   435                               exceptions[k].toString());
   436                     if (k < (exceptions.length - 1))
   437                         sb.append(',');
   438                 }
   439             }
   440             return sb.toString();
   441         } catch (Exception e) {
   442             return "<" + e + ">";
   443         }
   444     }
   445 
   446     /**
   447      * Invokes the underlying method represented by this {@code Method}
   448      * object, on the specified object with the specified parameters.
   449      * Individual parameters are automatically unwrapped to match
   450      * primitive formal parameters, and both primitive and reference
   451      * parameters are subject to method invocation conversions as
   452      * necessary.
   453      *
   454      * <p>If the underlying method is static, then the specified {@code obj}
   455      * argument is ignored. It may be null.
   456      *
   457      * <p>If the number of formal parameters required by the underlying method is
   458      * 0, the supplied {@code args} array may be of length 0 or null.
   459      *
   460      * <p>If the underlying method is an instance method, it is invoked
   461      * using dynamic method lookup as documented in The Java Language
   462      * Specification, Second Edition, section 15.12.4.4; in particular,
   463      * overriding based on the runtime type of the target object will occur.
   464      *
   465      * <p>If the underlying method is static, the class that declared
   466      * the method is initialized if it has not already been initialized.
   467      *
   468      * <p>If the method completes normally, the value it returns is
   469      * returned to the caller of invoke; if the value has a primitive
   470      * type, it is first appropriately wrapped in an object. However,
   471      * if the value has the type of an array of a primitive type, the
   472      * elements of the array are <i>not</i> wrapped in objects; in
   473      * other words, an array of primitive type is returned.  If the
   474      * underlying method return type is void, the invocation returns
   475      * null.
   476      *
   477      * @param obj  the object the underlying method is invoked from
   478      * @param args the arguments used for the method call
   479      * @return the result of dispatching the method represented by
   480      * this object on {@code obj} with parameters
   481      * {@code args}
   482      *
   483      * @exception IllegalAccessException    if this {@code Method} object
   484      *              is enforcing Java language access control and the underlying
   485      *              method is inaccessible.
   486      * @exception IllegalArgumentException  if the method is an
   487      *              instance method and the specified object argument
   488      *              is not an instance of the class or interface
   489      *              declaring the underlying method (or of a subclass
   490      *              or implementor thereof); if the number of actual
   491      *              and formal parameters differ; if an unwrapping
   492      *              conversion for primitive arguments fails; or if,
   493      *              after possible unwrapping, a parameter value
   494      *              cannot be converted to the corresponding formal
   495      *              parameter type by a method invocation conversion.
   496      * @exception InvocationTargetException if the underlying method
   497      *              throws an exception.
   498      * @exception NullPointerException      if the specified object is null
   499      *              and the method is an instance method.
   500      * @exception ExceptionInInitializerError if the initialization
   501      * provoked by this method fails.
   502      */
   503     public Object invoke(Object obj, Object... args)
   504         throws IllegalAccessException, IllegalArgumentException,
   505            InvocationTargetException
   506     {
   507         final boolean nonStatic = (getModifiers() & Modifier.STATIC) == 0;
   508         if (nonStatic && obj == null) {
   509             throw new NullPointerException();
   510         }
   511         Class[] types = getParameterTypes();
   512         if (types.length != args.length) {
   513             throw new IllegalArgumentException("Types len " + types.length + " args: " + args.length);
   514         } else {
   515             args = args.clone();
   516             for (int i = 0; i < types.length; i++) {
   517                 Class c = types[i];
   518                 if (c.isPrimitive() && args[i] != null) {
   519                     args[i] = toPrimitive(args[i]);
   520                 }
   521             }
   522         }
   523         Object res = invokeTry(nonStatic, this, obj, args);
   524         if (getReturnType().isPrimitive()) {
   525             res = fromPrimitive(getReturnType(), res);
   526         }
   527         return res;
   528     }
   529     
   530     @JavaScriptBody(args = { "st", "method", "self", "args" }, body =
   531           "var p; var cll;\n"
   532         + "if (st) {\n"
   533         + "  cll = self[method._name() + '__' + method._sig()];\n"
   534         + "  p = args;\n"
   535         + "} else {\n"
   536         + "  p = args;\n"
   537         + "  cll = method._data();"
   538         + "}\n"
   539         + "return cll.apply(self, p);\n"
   540     )
   541     private static native Object invoke0(boolean isStatic, Method m, Object self, Object[] args);
   542     
   543     private static Object invokeTry(boolean isStatic, Method m, Object self, Object[] args)
   544     throws InvocationTargetException {
   545         try {
   546             return invoke0(isStatic, m, self, args);
   547         } catch (Throwable ex) {
   548             throw new InvocationTargetException(ex, ex.getMessage());
   549         }
   550     }
   551 
   552     static Object fromPrimitive(Class<?> type, Object o) {
   553         if (samePrimitive(type, Integer.TYPE)) {
   554             return fromRaw(Integer.class, "valueOf__Ljava_lang_Integer_2I", o);
   555         }
   556         if (samePrimitive(type, Long.TYPE)) {
   557             return fromRaw(Long.class, "valueOf__Ljava_lang_Long_2J", o);
   558         }
   559         if (samePrimitive(type, Double.TYPE)) {
   560             return fromRaw(Double.class, "valueOf__Ljava_lang_Double_2D", o);
   561         }
   562         if (samePrimitive(type, Float.TYPE)) {
   563             return fromRaw(Float.class, "valueOf__Ljava_lang_Float_2F", o);
   564         }
   565         if (samePrimitive(type, Byte.TYPE)) {
   566             return fromRaw(Byte.class, "valueOf__Ljava_lang_Byte_2B", o);
   567         }
   568         if (samePrimitive(type, Boolean.TYPE)) {
   569             return fromRaw(Boolean.class, "valueOf__Ljava_lang_Boolean_2Z", o);
   570         }
   571         if (samePrimitive(type, Short.TYPE)) {
   572             return fromRaw(Short.class, "valueOf__Ljava_lang_Short_2S", o);
   573         }
   574         if (samePrimitive(type, Character.TYPE)) {
   575             return fromRaw(Character.class, "valueOf__Ljava_lang_Character_2C", o);
   576         }
   577         if (type.getName().equals("void")) {
   578             return null;
   579         }
   580         throw new IllegalStateException("Can't convert " + o);
   581     }
   582     static boolean samePrimitive(Class<?> c1, Class<?> c2) {
   583         if (c1 == c2) {
   584             return true;
   585         }
   586         if (c1.isPrimitive()) {
   587             return c1.getName().equals(c2.getName());
   588         }
   589         return false;
   590     }
   591 
   592     static String findArraySignature(Class<?> type) {
   593         if (!type.isPrimitive()) {
   594             return "[L" + type.getName().replace('.', '/') + ";";
   595         }
   596         if (samePrimitive(type, Integer.TYPE)) {
   597             return "[I";
   598         }
   599         if (samePrimitive(type, Long.TYPE)) {
   600             return "[J";
   601         }
   602         if (samePrimitive(type, Double.TYPE)) {
   603             return "[D";
   604         }
   605         if (samePrimitive(type, Float.TYPE)) {
   606             return "[F";
   607         }
   608         if (samePrimitive(type, Byte.TYPE)) {
   609             return "[B";
   610         }
   611         if (samePrimitive(type, Boolean.TYPE)) {
   612             return "[Z";
   613         }
   614         if (samePrimitive(type, Short.TYPE)) {
   615             return "[S";
   616         }
   617         if (samePrimitive(type, Character.TYPE)) {
   618             return "[C";
   619         }
   620         throw new IllegalStateException("Can't create array for " + type);
   621     }
   622     
   623     @JavaScriptBody(args = { "cls", "m", "o" }, 
   624         body = "return cls.cnstr(false)[m](o);"
   625     )
   626     private static native Integer fromRaw(Class<?> cls, String m, Object o);
   627 
   628     @JavaScriptBody(args = { "o" }, body = "return o.valueOf();")
   629     static native Object toPrimitive(Object o);
   630     
   631     /**
   632      * Returns {@code true} if this method is a bridge
   633      * method; returns {@code false} otherwise.
   634      *
   635      * @return true if and only if this method is a bridge
   636      * method as defined by the Java Language Specification.
   637      * @since 1.5
   638      */
   639     public boolean isBridge() {
   640         return (getModifiers() & Modifier.BRIDGE) != 0;
   641     }
   642 
   643     /**
   644      * Returns {@code true} if this method was declared to take
   645      * a variable number of arguments; returns {@code false}
   646      * otherwise.
   647      *
   648      * @return {@code true} if an only if this method was declared to
   649      * take a variable number of arguments.
   650      * @since 1.5
   651      */
   652     public boolean isVarArgs() {
   653         return (getModifiers() & Modifier.VARARGS) != 0;
   654     }
   655 
   656     /**
   657      * Returns {@code true} if this method is a synthetic
   658      * method; returns {@code false} otherwise.
   659      *
   660      * @return true if and only if this method is a synthetic
   661      * method as defined by the Java Language Specification.
   662      * @since 1.5
   663      */
   664     public boolean isSynthetic() {
   665         return Modifier.isSynthetic(getModifiers());
   666     }
   667 
   668     @JavaScriptBody(args = { "ac" }, 
   669         body = 
   670           "var a = this._data().anno;\n"
   671         + "if (a) {\n"
   672         + "  a = a['L' + ac.jvmName + ';'];\n"
   673         + "}\n"
   674         + "return a ? a : null;"
   675     )
   676     private native Object getAnnotationData(Class<?> annotationClass);
   677 
   678     @JavaScriptBody(args = {},
   679         body =
   680           "var a = this._data().anno;\n"
   681         + "if (a) {\n"
   682         + "  var arr = [];\n"
   683         + "  for (p in a) {\n"
   684         + "    arr.push(p);\n"
   685         + "  }\n"
   686         + "  return arr;\n"
   687         + "} else return [];\n"
   688     )
   689     private native String[] getAnnotationNames();
   690     
   691     /**
   692      * @throws NullPointerException {@inheritDoc}
   693      * @since 1.5
   694      */
   695     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
   696         Object data = getAnnotationData(annotationClass);
   697         return data == null ? null : AnnotationImpl.create(annotationClass, data);
   698     }
   699 
   700     /**
   701      * @since 1.5
   702      */
   703     public Annotation[] getDeclaredAnnotations()  {
   704         String[] arr = getAnnotationNames();
   705         Annotation[] res = new Annotation[arr.length];
   706         for (int i = 0; i < arr.length; i++) {
   707             String forName = arr[i].substring(1, arr[i].length() - 1).replace('/', '.');
   708             final Class<? extends Annotation> annoType;
   709             try {
   710                 annoType = Class.forName(forName).asSubclass(Annotation.class);
   711             } catch (ClassNotFoundException ex) {
   712                 throw new IllegalStateException(forName);
   713             }
   714             res[i] = getAnnotation(annoType);
   715         }
   716         return res;
   717     }
   718 
   719     /**
   720      * Returns the default value for the annotation member represented by
   721      * this {@code Method} instance.  If the member is of a primitive type,
   722      * an instance of the corresponding wrapper type is returned. Returns
   723      * null if no default is associated with the member, or if the method
   724      * instance does not represent a declared member of an annotation type.
   725      *
   726      * @return the default value for the annotation member represented
   727      *     by this {@code Method} instance.
   728      * @throws TypeNotPresentException if the annotation is of type
   729      *     {@link Class} and no definition can be found for the
   730      *     default class value.
   731      * @since  1.5
   732      */
   733     public Object getDefaultValue() {
   734         throw new UnsupportedOperationException();
   735     }
   736 
   737     /**
   738      * Returns an array of arrays that represent the annotations on the formal
   739      * parameters, in declaration order, of the method represented by
   740      * this {@code Method} object. (Returns an array of length zero if the
   741      * underlying method is parameterless.  If the method has one or more
   742      * parameters, a nested array of length zero is returned for each parameter
   743      * with no annotations.) The annotation objects contained in the returned
   744      * arrays are serializable.  The caller of this method is free to modify
   745      * the returned arrays; it will have no effect on the arrays returned to
   746      * other callers.
   747      *
   748      * @return an array of arrays that represent the annotations on the formal
   749      *    parameters, in declaration order, of the method represented by this
   750      *    Method object
   751      * @since 1.5
   752      */
   753     public Annotation[][] getParameterAnnotations() {
   754         throw new UnsupportedOperationException();
   755     }
   756 
   757     static {
   758         MethodImpl.INSTANCE = new MethodImpl() {
   759             protected Method create(Class<?> declaringClass, String name, Object data, String sig) {
   760                 return new Method(declaringClass, name, data, sig);
   761             }
   762 
   763             @Override
   764             protected Constructor create(Class<?> declaringClass, Object data, String sig) {
   765                 return new Constructor(declaringClass, data, sig);
   766             }
   767         };
   768     }
   769     
   770     //
   771     // helper methods for Array
   772     //
   773     
   774     @JavaScriptBody(args = { "primitive", "sig", "fn", "length" }, body =
   775           "var arr = new Array(length);\n"
   776         + "var value = primitive ? 0 : null;\n"
   777         + "for(var i = 0; i < length; i++) arr[i] = value;\n"
   778         + "Object.defineProperty(arr, 'jvmName', { 'configurable': true, 'writable': true, 'value': sig });\n"
   779         + "Object.defineProperty(arr, 'fnc', { 'configurable': true, 'writable': true, 'value' : fn });\n"
   780 //        + "java.lang.System.out.println('Assigned ' + arr.jvmName + ' fn: ' + (!!arr.fnc));\n"
   781         + "return arr;"
   782     )
   783     static native Object newArray(boolean primitive, String sig, Object fn, int length);
   784     
   785     @JavaScriptBody(args = { "arr" }, body = "return arr.length;")
   786     static native int arrayLength(Object arr);
   787     
   788     @JavaScriptBody(args = { "cntstr" }, body = "return cntstr(false).constructor.$class;")
   789     static native Class<?> classFromFn(Object cntstr);
   790     @JavaScriptBody(args = { "array", "index" }, body = "return array[index];")
   791     static native Object atArray(Object array, int index);
   792 
   793     @JavaScriptBody(args = { "array", "index", "v" }, body = "array[index] = v;")
   794     static native Object setArray(Object array, int index, Object v);
   795     
   796 }