1.获取某个对象的Class,也就是.class,一般是通过如下两种方式可以获得。
第一种方式:Class.forName("T"); T代表对象的名称(包括该对象的包名),如:Class.forName ("org.wsay.ttitfly.ReflectMethod");
第二种方式:T.class 即可,T代表该对象名称(不包括该对象的包名),如:ReflectMethod.class
还有一种独特的方式是专门针对int,long ..的包装对象Integer,Long...的,如Integer.Type 表示基
本类型 int 的 Class 实例
2, Method.invoke(Object o,Object...args),调用对象o的Method封装的方法,参数为args,args可以是个参数列表,也可以是个参数数组. 详细见下面例子.
package org.wsay.ttitfly;
import java.lang.reflect.Method;
public class ReflectMethod {
public static void main(String[] args)
{
try
{
Class rm = Class.forName("org.wsay.ttitfly.ReflectMethod"); //第一种方式获取该对象的Class
//Class rm = ReflectMethod.class;//第二种方式获得
//表示调用ReflectMethod的add方法,有2个int参数
Method method = rm.getMethod("add", Integer.TYPE,Integer.TYPE);
// Object []o = new Object[2];
// o[0] = new Integer(2);
// o[1] = new Integer(3);
Integer result = (Integer) method.invoke(new ReflectMethod(),2,3);//参数列表
// Integer result = (Integer) method.invoke(new ReflectMethod(),o);//参数数组
System.out.println(result.intValue());
}
catch (Exception e)
{
e.printStackTrace();
}
}
public int add(int a,int b)
{
return a+b;
}
}
打印结果为:5