参考这个 blog
http://iwtxokhtd.iteye.com/blog/359584
觉得用的比较多的就是 利用反射执行某个类中的某个方法,看看下面这个例子
package cn.com.xinli.test.reflect;
import java.lang.reflect.*;
/**
*通过反射执行类的方法
*/
class PerformMethod
{
//声明一个简单的方法,用于测试
public int add(int a,int b){
return a+b;
}
public static void main(String[] args)throws Exception
{
//获取本类的类对象
Class c=Class.forName("cn.com.xinli.test.reflect.PerformMethod");
Object []argList=new Object[2];
//传入37和43
argList[0]=new Integer(37);
argList[1]=new Integer(43);
//根据方法名和参数类型集合得到方法
Method[] m=c.getMethods();
for(Method me: m)
{
if (me.getName().equals("add"))
{
System.out.println( me.invoke(c.newInstance(), argList));
}
}
}
}
本文提供了一个使用Java反射机制来执行指定类中特定方法的例子。通过Class类的forName方法加载目标类,并通过getMethod获取该类的方法。然后实例化类并调用invoke方法执行目标方法。
24万+

被折叠的 条评论
为什么被折叠?



