Java如何使用Method类调用方法?
本示例演示使用反射来调用类对象的方法。使用反射,我们可以使用给定的方法字符串名称来调用对象的方法。使用此方法时,我们需要捕捉的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;
}
}
热门推荐
10 服装超市开业祝福语简短
11 祝寺院师傅祝福语简短
12 工作花束祝福语简短英文
13 当选团员祝福语简短精辟
14 感恩老师祝福语简短精辟
15 祝福语朋友简短恋爱结婚
16 学生 牛年祝福语大全简短
17 顺利毕业家人祝福语简短
18 预祝成功祝福语英文简短