Home | History | Annotate | Download | only in src
      1 // Copyright 2006 The Android Open Source Project
      2 
      3 import java.lang.reflect.*;
      4 import java.io.IOException;
      5 import java.util.Collections;
      6 
      7 /**
      8  * Reflection test.
      9  */
     10 public class Main {
     11     void printMethodInfo(Method meth) {
     12         Class[] params, exceptions;
     13         int i;
     14 
     15         System.out.println("Method name is " + meth.getName());
     16         System.out.println(" Declaring class is "
     17             + meth.getDeclaringClass().getName());
     18         params = meth.getParameterTypes();
     19         for (i = 0; i < params.length; i++)
     20             System.out.println(" Arg " + i + ": " + params[i].getName());
     21         exceptions = meth.getExceptionTypes();
     22         for (i = 0; i < exceptions.length; i++)
     23             System.out.println(" Exc " + i + ": " + exceptions[i].getName());
     24         System.out.println(" Return type is " + meth.getReturnType().getName());
     25         System.out.println(" Access flags are 0x"
     26             + Integer.toHexString(meth.getModifiers()));
     27         //System.out.println(" GenericStr is " + meth.toGenericString());
     28     }
     29 
     30     void printFieldInfo(Field field) {
     31         System.out.println("Field name is " + field.getName());
     32         System.out.println(" Declaring class is "
     33             + field.getDeclaringClass().getName());
     34         System.out.println(" Field type is " + field.getType().getName());
     35         System.out.println(" Access flags are 0x"
     36             + Integer.toHexString(field.getModifiers()));
     37     }
     38 
     39     private void showStrings(Target instance)
     40         throws NoSuchFieldException, IllegalAccessException {
     41 
     42         Class target = Target.class;
     43         String one, two, three, four;
     44         Field field = null;
     45 
     46         field = target.getField("string1");
     47         one = (String) field.get(instance);
     48 
     49         field = target.getField("string2");
     50         two = (String) field.get(instance);
     51 
     52         field = target.getField("string3");
     53         three = (String) field.get(instance);
     54 
     55         System.out.println("  ::: " + one + ":" + two + ":" + three);
     56     }
     57 
     58     public void run() {
     59         Class target = Target.class;
     60         Method meth = null;
     61         Field field = null;
     62         boolean excep;
     63 
     64         try {
     65             meth = target.getMethod("myMethod", new Class[] { int.class });
     66 
     67             if (meth.getDeclaringClass() != target)
     68                 throw new RuntimeException();
     69             printMethodInfo(meth);
     70 
     71             meth = target.getMethod("myMethod", new Class[] { float.class });
     72             printMethodInfo(meth);
     73 
     74             meth = target.getMethod("myNoargMethod", (Class[]) null);
     75             printMethodInfo(meth);
     76 
     77             meth = target.getMethod("myMethod",
     78                 new Class[] { String[].class, float.class, char.class });
     79             printMethodInfo(meth);
     80 
     81             Target instance = new Target();
     82             Object[] argList = new Object[] {
     83                 new String[] { "hi there" },
     84                 new Float(3.1415926f),
     85                 new Character('Q')
     86             };
     87             System.out.println("Before, float is "
     88                 + ((Float)argList[1]).floatValue());
     89 
     90             Integer boxval;
     91             boxval = (Integer) meth.invoke(instance, argList);
     92             System.out.println("Result of invoke: " + boxval.intValue());
     93 
     94             System.out.println("Calling no-arg void-return method");
     95             meth = target.getMethod("myNoargMethod", (Class[]) null);
     96             meth.invoke(instance, (Object[]) null);
     97 
     98             /* try invoking a method that throws an exception */
     99             meth = target.getMethod("throwingMethod", (Class[]) null);
    100             try {
    101                 meth.invoke(instance, (Object[]) null);
    102                 System.out.println("GLITCH: didn't throw");
    103             } catch (InvocationTargetException ite) {
    104                 System.out.println("Invoke got expected exception:");
    105                 System.out.println(ite.getClass().getName());
    106                 System.out.println(ite.getCause());
    107             }
    108             catch (Exception ex) {
    109                 System.out.println("GLITCH: invoke got wrong exception:");
    110                 ex.printStackTrace();
    111             }
    112             System.out.println("");
    113 
    114 
    115             field = target.getField("string1");
    116             if (field.getDeclaringClass() != target)
    117                 throw new RuntimeException();
    118             printFieldInfo(field);
    119             String strVal = (String) field.get(instance);
    120             System.out.println("  string1 value is '" + strVal + "'");
    121 
    122             showStrings(instance);
    123 
    124             field.set(instance, new String("a new string"));
    125             strVal = (String) field.get(instance);
    126             System.out.println("  string1 value is now '" + strVal + "'");
    127 
    128             showStrings(instance);
    129 
    130             try {
    131                 field.set(instance, new Object());
    132                 System.out.println("WARNING: able to store Object into String");
    133             }
    134             catch (IllegalArgumentException iae) {
    135                 System.out.println("  got expected illegal obj store exc");
    136             }
    137 
    138 
    139             try {
    140                 String four;
    141                 field = target.getField("string4");
    142                 four = (String) field.get(instance);
    143                 System.out.println("WARNING: able to access string4: "
    144                     + four);
    145             }
    146             catch (IllegalAccessException iae) {
    147                 System.out.println("  got expected access exc");
    148             }
    149             catch (NoSuchFieldException nsfe) {
    150                 System.out.println("  got the other expected access exc");
    151             }
    152             try {
    153                 String three;
    154                 field = target.getField("string3");
    155                 three = (String) field.get(this);
    156                 System.out.println("WARNING: able to get string3 in wrong obj: "
    157                     + three);
    158             }
    159             catch (IllegalArgumentException iae) {
    160                 System.out.println("  got expected arg exc");
    161             }
    162 
    163             /*
    164              * Try setting a field to null.
    165              */
    166             String four;
    167             field = target.getDeclaredField("string3");
    168             field.set(instance, null);
    169 
    170             /*
    171              * Do some stuff with long.
    172              */
    173             long longVal;
    174             field = target.getField("pubLong");
    175             longVal = field.getLong(instance);
    176             System.out.println("pubLong initial value is " +
    177                 Long.toHexString(longVal));
    178             field.setLong(instance, 0x9988776655443322L);
    179             longVal = field.getLong(instance);
    180             System.out.println("pubLong new value is " +
    181                 Long.toHexString(longVal));
    182 
    183 
    184             field = target.getField("superInt");
    185             if (field.getDeclaringClass() == target)
    186                 throw new RuntimeException();
    187             printFieldInfo(field);
    188             int intVal = field.getInt(instance);
    189             System.out.println("  superInt value is " + intVal);
    190             Integer boxedIntVal = (Integer) field.get(instance);
    191             System.out.println("  superInt boxed is " + boxedIntVal);
    192 
    193             field.set(instance, new Integer(20202));
    194             intVal = field.getInt(instance);
    195             System.out.println("  superInt value is now " + intVal);
    196             field.setShort(instance, (short)30303);
    197             intVal = field.getInt(instance);
    198             System.out.println("  superInt value (from short) is now " +intVal);
    199             field.setInt(instance, 40404);
    200             intVal = field.getInt(instance);
    201             System.out.println("  superInt value is now " + intVal);
    202             try {
    203                 field.set(instance, new Long(123));
    204                 System.out.println("FAIL: expected exception not thrown");
    205             }
    206             catch (IllegalArgumentException iae) {
    207                 System.out.println("  got expected long->int failure");
    208             }
    209             try {
    210                 field.setLong(instance, 123);
    211                 System.out.println("FAIL: expected exception not thrown");
    212             }
    213             catch (IllegalArgumentException iae) {
    214                 System.out.println("  got expected long->int failure");
    215             }
    216             try {
    217                 field.set(instance, new String("abc"));
    218                 System.out.println("FAIL: expected exception not thrown");
    219             }
    220             catch (IllegalArgumentException iae) {
    221                 System.out.println("  got expected string->int failure");
    222             }
    223 
    224             try {
    225                 field.getShort(instance);
    226                 System.out.println("FAIL: expected exception not thrown");
    227             }
    228             catch (IllegalArgumentException iae) {
    229                 System.out.println("  got expected int->short failure");
    230             }
    231 
    232             field = target.getField("superClassInt");
    233             printFieldInfo(field);
    234             int superClassIntVal = field.getInt(instance);
    235             System.out.println("  superClassInt value is " + superClassIntVal);
    236 
    237             field = target.getField("staticDouble");
    238             printFieldInfo(field);
    239             double staticDoubleVal = field.getDouble(null);
    240             System.out.println("  staticDoubleVal value is " + staticDoubleVal);
    241 
    242             try {
    243                 field.getLong(instance);
    244                 System.out.println("FAIL: expected exception not thrown");
    245             }
    246             catch (IllegalArgumentException iae) {
    247                 System.out.println("  got expected double->long failure");
    248             }
    249 
    250             excep = false;
    251             try {
    252                 field = target.getField("aPrivateInt");
    253                 printFieldInfo(field);
    254             }
    255             catch (NoSuchFieldException nsfe) {
    256                 System.out.println("as expected: aPrivateInt not found");
    257                 excep = true;
    258             }
    259             if (!excep)
    260                 System.out.println("BUG: got aPrivateInt");
    261 
    262 
    263             field = target.getField("constantString");
    264             printFieldInfo(field);
    265             String val = (String) field.get(instance);
    266             System.out.println("  Constant test value is " + val);
    267 
    268 
    269             field = target.getField("cantTouchThis");
    270             printFieldInfo(field);
    271             intVal = field.getInt(instance);
    272             System.out.println("  cantTouchThis is " + intVal);
    273             try {
    274                 field.setInt(instance, 99);
    275                 System.out.println("ERROR: set-final succeeded\n");
    276             } catch (IllegalAccessException iae) {
    277                 System.out.println("  got expected set-final failure\n");
    278             }
    279             intVal = field.getInt(instance);
    280             System.out.println("  cantTouchThis is now " + intVal);
    281 
    282             Constructor<Target> cons;
    283             Target targ;
    284             Object[] args;
    285 
    286             cons = target.getConstructor(new Class[] { int.class,float.class });
    287             args = new Object[] { new Integer(7), new Float(3.3333) };
    288             System.out.println("cons modifiers=" + cons.getModifiers());
    289             targ = cons.newInstance(args);
    290             targ.myMethod(17);
    291 
    292         }
    293         catch (Exception ex) {
    294             System.out.println("----- unexpected exception -----");
    295             ex.printStackTrace();
    296         }
    297 
    298         System.out.println("ReflectTest done!");
    299     }
    300 
    301     public static void checkType() {
    302         Method m;
    303 
    304         try {
    305             m = Collections.class.getDeclaredMethod("checkType",
    306                             Object.class, Class.class);
    307         } catch (NoSuchMethodException nsme) {
    308             nsme.printStackTrace();
    309             return;
    310         }
    311 
    312         m.setAccessible(true);
    313         try {
    314             m.invoke(null, new Object(), Object.class);
    315         } catch (IllegalAccessException iae) {
    316             iae.printStackTrace();
    317             return;
    318         } catch (InvocationTargetException ite) {
    319             ite.printStackTrace();
    320             return;
    321         }
    322 
    323         try {
    324             System.out.println("checkType invoking null");
    325             m.invoke(null, new Object(), int.class);
    326             System.out.println("ERROR: should throw InvocationTargetException");
    327         } catch (InvocationTargetException ite) {
    328             System.out.println("checkType got expected exception");
    329         } catch (IllegalAccessException iae) {
    330             iae.printStackTrace();
    331             return;
    332         }
    333     }
    334 
    335     public static void checkInit() {
    336         Class niuClass = NoisyInitUser.class;
    337         Method[] methods;
    338 
    339         methods = niuClass.getDeclaredMethods();
    340         System.out.println("got methods");
    341         /* neither NoisyInit nor NoisyInitUser should be initialized yet */
    342         NoisyInitUser niu = new NoisyInitUser();
    343         NoisyInit ni = new NoisyInit();
    344     }
    345 
    346     public static void main(String[] args) {
    347         Main test = new Main();
    348         test.run();
    349 
    350         checkType();
    351         checkInit();
    352     }
    353 }
    354 
    355 
    356 class SuperTarget {
    357     public SuperTarget() {
    358         System.out.println("SuperTarget constructor ()V");
    359         superInt = 1010101;
    360         superClassInt = 1010102;
    361     }
    362 
    363     public int myMethod(float floatArg) {
    364         System.out.println("myMethod (F)I " + floatArg);
    365         return 6;
    366     }
    367 
    368     public int superInt;
    369     public static int superClassInt;
    370 }
    371 
    372 class Target extends SuperTarget {
    373     public Target() {
    374         System.out.println("Target constructor ()V");
    375     }
    376 
    377     public Target(int ii, float ff) {
    378         System.out.println("Target constructor (IF)V : ii="
    379             + ii + " ff=" + ff);
    380         anInt = ii;
    381     }
    382 
    383     public int myMethod(int intarg) throws NullPointerException, IOException {
    384         System.out.println("myMethod (I)I");
    385         System.out.println(" arg=" + intarg + " anInt=" + anInt);
    386         return 5;
    387     }
    388 
    389     public int myMethod(String[] strarg, float f, char c) {
    390         System.out.println("myMethod: " + strarg[0] + " " + f + " " + c + " !");
    391         return 7;
    392     }
    393 
    394     public static void myNoargMethod() {
    395         System.out.println("myNoargMethod ()V");
    396     }
    397 
    398     public void throwingMethod() {
    399         System.out.println("throwingMethod");
    400         throw new NullPointerException("gratuitous throw!");
    401     }
    402 
    403     public void misc() {
    404         System.out.println("misc");
    405     }
    406 
    407     public int anInt;
    408     public String string1 = "hey";
    409     public String string2 = "yo";
    410     public String string3 = "there";
    411     private String string4 = "naughty";
    412     public static final String constantString = "a constant string";
    413     private int aPrivateInt;
    414 
    415     public final int cantTouchThis = 77;
    416 
    417     public long pubLong = 0x1122334455667788L;
    418 
    419     public static double staticDouble = 3.3;
    420 }
    421 
    422 class NoisyInit {
    423     static {
    424         System.out.println("NoisyInit is initializing");
    425         //Throwable th = new Throwable();
    426         //th.printStackTrace();
    427     }
    428 }
    429 
    430 class NoisyInitUser {
    431     static {
    432         System.out.println("NoisyInitUser is initializing");
    433     }
    434     public void createNoisyInit(NoisyInit ni) {}
    435 }
    436