本示例演示使用反射来调用类对象的方法。使用反射,我们可以使用给定的方法字符串名称来调用对象的方法。使用此方法时,我们需要捕捉的NoSuchMethodException,IllegalAccessException和InvocationTargetException。
package org.nhooo.example.lang; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; public class InvokingMethod { public static void main(String[] args) { InvokingMethod object = new InvokingMethod(); Class clazz = object.getClass(); try { // 调用add(int,int)方法 Method method = clazz.getMethod("add", new Class[] {int.class, int.class}); Object result = method.invoke(object, new Object[] {10, 10}); System.out.println("Result = " + result); // 调用乘法(int,int)方法 method = clazz.getMethod("multiply", new Class[] {int.class, int.class}); result = method.invoke(object, new Object[] {10, 10}); System.out.println("Result = " + result); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } public int add(int numberA, int numberB) { return numberA + numberB; } public int multiply(int numberA, int numberB) { return numberA * numberB; } public double div(int numberA, int numberB) { return numberA / numberB; } }