Elliott Hughes | aaa5edc | 2012-05-16 15:54:30 -0700 | [diff] [blame] | 1 | import java.lang.reflect.Field; |
| 2 | import java.lang.reflect.Method; |
| 3 | |
| 4 | public class Main { |
| 5 | public static void main(String[] args) throws Exception { |
| 6 | // Can't assign Integer to a String field. |
| 7 | try { |
| 8 | Field field = A.class.getField("b"); |
| 9 | field.set(new A(), 5); |
| 10 | } catch (IllegalArgumentException expected) { |
| 11 | System.out.println(expected.getMessage()); |
| 12 | } |
| 13 | |
| 14 | // Can't unbox null to a primitive. |
| 15 | try { |
| 16 | Field field = A.class.getField("i"); |
| 17 | field.set(new A(), null); |
| 18 | } catch (IllegalArgumentException expected) { |
| 19 | System.out.println(expected.getMessage()); |
| 20 | } |
| 21 | |
| 22 | // Can't unbox String to a primitive. |
| 23 | try { |
| 24 | Field field = A.class.getField("i"); |
| 25 | field.set(new A(), "hello, world!"); |
| 26 | } catch (IllegalArgumentException expected) { |
| 27 | System.out.println(expected.getMessage()); |
| 28 | } |
| 29 | |
| 30 | // Can't pass an Integer as a String. |
| 31 | try { |
| 32 | Method m = A.class.getMethod("m", int.class, String.class); |
| 33 | m.invoke(new A(), 2, 2); |
| 34 | } catch (IllegalArgumentException expected) { |
| 35 | System.out.println(expected.getMessage()); |
| 36 | } |
| 37 | |
| 38 | // Can't pass null as an int. |
| 39 | try { |
| 40 | Method m = A.class.getMethod("m", int.class, String.class); |
| 41 | m.invoke(new A(), null, ""); |
| 42 | } catch (IllegalArgumentException expected) { |
| 43 | System.out.println(expected.getMessage()); |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | class A { |
| 49 | public String b; |
| 50 | public int i; |
| 51 | public void m(int i, String s) {} |
| 52 | } |