4、java反射机制例子
java反射机制例子:
1.新建Calculator.java
package invoke;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
2.新建CalculatorTest.java,作为测试,采用反射机制获取到Calculator的add方法:
package invoke;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import invoke.Calculator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CalculatorTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testAdd() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
//方法中所需要的参数
Integer[] input = new Integer[]{new Integer(1), new Integer(2)};
Class clazz = Class.forName("invoke.Calculator");
//获取add方法的method
@SuppressWarnings("unchecked")
Method method = clazz.getMethod("add", new Class[]{int.class, int.class});
Integer output = (Integer) method.invoke(new Calculator(), input);
System.out.println("1 + 2 =" + output.intValue());
}
}
3.运行结果:1 + 2 = 3