java反射之dynamic invocation与原生类型
/** * Using primitives with dynamic invocation * * @author sdcuike * * Created At 2016年8月28日 下午5:44:55 */ public class UsingPrimitivesWithDynamicInvocation { public static void main(String[] args) throws ReflectiveOperationException, SecurityException { DemoClass demoClass = new DemoClass(); Method method = demoClass.getClass().getMethod("getAge", new Class[] { int.class }); Object invoke = method.invoke(demoClass, Integer.valueOf(11)); System.out.println(invoke.getClass()); } public static class DemoClass { public int getAge(int age) { return age; } } }
/** * Using primitives with dynamic invocation * * @author sdcuike * * Created At 2016年8月28日 下午5:44:55 */ public class UsingPrimitivesWithDynamicInvocation { public static void main(String[] args) throws ReflectiveOperationException, SecurityException { DemoClass demoClass = new DemoClass(); Method method = demoClass.getClass().getMethod("getAge", new Class[] { int.class }); Object invoke = method.invoke(demoClass, Integer.valueOf(11)); System.out.println(invoke.getClass());// class java.lang.Integer int age = ((Integer) invoke).intValue();// 需要手动拆箱操作 System.out.println(age); Method method2 = demoClass.getClass().getMethod("print", new Class[] {}); Object invoke2 = method2.invoke(demoClass); System.out.println(invoke2);// null } public static class DemoClass { public int getAge(int age) { return age; } public void print() { System.out.println("=="); } } }
/** * Using primitives with dynamic invocation * * @author sdcuike * * Created At 2016年8月28日 下午5:44:55 */ public class UsingPrimitivesWithDynamicInvocation { public static void main(String[] args) throws ReflectiveOperationException, SecurityException { // 自动拆箱操作参数,返回值自动装箱操作 DemoClass demoClass = new DemoClass(); Method method = demoClass.getClass().getMethod("getAge", new Class[] { int.class }); Object invoke = method.invoke(demoClass, Integer.valueOf(11)); System.out.println(invoke.getClass());// class java.lang.Integer int age = ((Integer) invoke).intValue();// 需要手动拆箱操作 System.out.println(age); // 无返回值情况 Method method2 = demoClass.getClass().getMethod("print", new Class[] {}); Object invoke2 = method2.invoke(demoClass); System.out.println(invoke2);// null // 当方法返回原生类型数组的时候,不进行装箱操作 Method getArray = demoClass.getClass().getMethod("getArray", new Class[] {}); Object invoke3 = getArray.invoke(demoClass); System.out.println(invoke3.getClass());// class [I int[] array = (int[]) invoke3; for (int i : array) { System.out.println(i); } } public static class DemoClass { public int getAge(int age) { return age; } public int[] getArray() { return new int[] { 11, 66, 88 }; } public void print() { System.out.println("=="); } } }
Java Reflection in Action 1.6.2 Using primitives with dynamic invocation ©2005 by Manning Publications Co