码迷,mamicode.com
首页 > 编程语言 > 详细

java中的反射,invoke方法

时间:2015-10-19 11:02:01      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

invoke,就是通过函数名反射调用相应的函数。以下代码简单地介绍了java反射中invoke方法

package org.curry.tool;
import java.lang.reflect.Method;
public class InvokeMethods {
public static void main(String[] args) {
  Employee emp = new Employee();
  Class cl = emp.getClass();//是Class,而不是class
  // getClass获得emp对象所属的类型的对象,Class就是描述类的类          
  // Class是专门用来描述类的类,比如描述某个类有那些字段,方法,构造器等等!
  try {
   // getMethod方法第一个参数指定一个需要调用的方法名称,这里是Employee类的setAge方法,
   // 第二个参数是需要调用方法的参数类型列表,是参数类型!如无参数可以指定null或者省略 
   // 该方法返回一个方法对象 
   //参数必须和方法中一样,int和Integer,double和Double被视为不同的类型
   Method sAge = cl.getMethod("setAge", new Class[] { int.class });
   Method gAge = cl.getMethod("getAge", null);
   Method pName = cl.getMethod("printName", new Class[] { String.class });
   Object[] args1 = { new Integer(25) };
   // invoke方法中,第二个参数为参数列表,该参数列表是一个object[]数组
   // emp为隐式参数该方法不是静态方法必须指定
   sAge.invoke(emp, args1);//通过setter方法赋值
   Integer AGE = (Integer) gAge.invoke(emp, null);//通过getter方法返回值
   int age = AGE.intValue();//Integer转换成int
   System.out.println("The Employee Age is: " + age);
   Object[] args3 = { new String("Jack") };
   pName.invoke(emp, args3);
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.exit(0);
 }
}
class Employee {
 // 定义一个员工类  
 public Employee() {
  age = 0;
  name = null;
 }
 // 将要被调用的方法  
 public void setAge(int a) {
  age = a;
 }
 // 将要被调用的方法  
 public int getAge() {
  return age;
 }
 // 将要被调用的方法
 public void printName(String n) {
  name = n;
  System.out.println("The Employee Name is: " + name);
 }
 private int age;
 private String name;
}

项目代码:

/**
 *利用keyName来对以search作为查询条件的结果集进行过滤
 /
public Map<Object, T> getMap(Search search,String keyName){
	List<T> entities=this.getBaseDao().search(search, DaoParam.SEARCH_OPTION_NORMAL);
	Map<Object, T> map=new LinkedHashMap<Object, T>();
	//通过参数keyName获得get方法名,比如getName,getAge
	String methodName="get"+keyName.substring(0,1).toUpperCase()+keyName.substring(1);
	for(T entity:entities){
		Object key=null;
		try {
		        //getter方法不需要参数
			Method method=entity.getClass().getMethod(methodName);
			//反射调用方法
			key=method.invoke(entity);
			if(key instanceof BasePojo){
			        //如果getter方法返回的是BasePojo类,那么以该BasePojo的id作为key
			        key=((BasePojo<?>)key).getId();
			}
			map.put(key, entity);

			} catch (Exception e) {
				logger.error(e,e);
			} 
		}
		entities=null;
		return map;
	}



java中的反射,invoke方法

标签:

原文地址:http://my.oschina.net/u/2331760/blog/518792

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!