1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class TestInvokeAnything { public static void main(String[] args) throws Exception { invokeAny( createObject("com.day.t1_factory.Student"), "exam", new Class[] {int.class, double.class, String.class}, 2, 10, "小明" ); Object o = createObject("com.day.t1_factory.Student"); invokeAny(o, "study", null, null); invokeAny(o, "study", new Class[] {Integer.class}, 100); }
public static void invokeAny(Object obj, String methodName, Class<?>[] types, Object...args) throws Exception { Class<?> c = obj.getClass(); Method m = c.getDeclaredMethod(methodName, types); m.invoke(obj, args); }
public static Object createObject(String className) { try { Class<?> c = Class.forName(className); return c.newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } }
|