JavaSE lecture61
反射,利用反射机制来获取类中的函数并 调用。
范例:
常规类 Calculator
package com.java.reflection;
public class Calculator {
public int add(int a,int b)
{
return a+b;
}
public int multiple(int a,int b)
{
return a*b;
}
public String feedback(String name, Integer in)
{
return "The User:"+name+" has logined for the "+in+" times";
}
}
method1:正规调用类函数
method2: 反射机制调用类函数
package com.java.reflection;
import java.lang.reflect.Method;
public class ReflectionTest {
public static void main(String[] args) throws Exception {
// method 1 方式一:正规调用。
Calculator cal = new Calculator();
int sum = cal.add(67, 33);
int mul = cal.multiple(12, 5);
String str = cal.feedback("clark", Integer.valueOf(5));
System.out.println("sum=" + sum + " mul=" + mul + " " + str);
System.out
.println("---------------The following is Using Reflection------------------");
// method 2 方式二:反射获取类的方法并调用。
// Class<?> classType=Class.forName("com.java.reflection.Calculator");
//两种不同的方式获取类的类型
Class<?> classType = Calculator.class;
Method method = classType.getMethod("multiple", int.class, int.class);
Object testCase1 = classType.newInstance();
Object testCase2 = classType.newInstance();
Object testCase3 = classType.newInstance();
// 判断newInstance出来的实例 是否为Calculator的实例。
System.out.println(testCase3 instanceof Calculator);
Object o1 = method.invoke(testCase2, 30, 2);
Object o2 = method.invoke(testCase3, 15, 10);
System.out.println("30 X 2= " + (Integer) o1 + " 15 X 10="
+ (Integer) o2);
// 创造新的method方法,这次在testCase2上调用。
Method method2 = classType.getMethod("feedback", String.class,
Integer.class);
String str2 = (String) method2.invoke(testCase1, "clark.J", 5);
System.out.println(str2);
}
}
输出:
附:
两种不同的方式获取类的类型
Class<?> classType=Class.forName("com.java.reflection.Calculator");
Class<?> classType = Calculator.class;
Calculator call=new Calculator();
Class<?> classType= call.getClass();