`
8366
  • 浏览: 800091 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

Java 反射

阅读更多

参考这个 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));
			 }
	 
 }
 }   
}  

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics