invoke是在函数名称反射中调用相应的函数。 下面的代码简要介绍了java反射的invoke方法
packageorg.curry.tool;
importjava.lang.reflect.Method;
publicclassInvokeMethods{
publicstaticvoidmain (字符串[ ] args ) {
Employeeemp=newEmployee (;
Classcl=emp.getClass (; 不是//Class而是class
//getClass是获取emp对象所属类型的对象并描述类的类
//Class是专门用于编写类的类,例如,描述一个类具有这些字段、方法、构造函数等!
try{
//getMethod方法的第一个参数指定要调用的方法名称。 这里是Employee类的setAge方法。
//第二个参数是必须调用方法的参数类型列表,它是参数类型! 如果没有参数,则可以指定null或省略
//此方法返回方法对象
//参数必须与方法相同,int和Integer、double和double被视为不同的类型
methods age=cl.get method (' setage ',newClass[]{int.class} );
method gage=cl.get method (' get age ',null );
method pname=cl.get method (' print name ',newClass[]{String.class} );
object[]args1={newinteger(25} );
//invoke方法的第二个参数是参数列表,该参数列表是object[]数组
//emp是隐式参数,必须指定此方法而不是静态方法
sage.invoke(EMP,args1); 用setter方法赋值
integerage=(integer ) gage.invoke ) EMP,空值; 用getter方法返回值
intage=AGE.intValue (; //Integer被转换为int
system.out.println (theemployeeageis : ) age;
object [ ] args3={ new string (' jack ' };
pname.invoke(EMP,args3);
}catch(exceptione ) {
e .打印堆栈跟踪(;
}
系统. exit (0;
}
}
类employee {
//定义员工类
公共雇员() }
age=0;
名称=null;
}
//要调用的方法
公共语音设置(inta ) {
age=a;
}
//要调用的方法
publicintgetAge () }
返回age;
}
//要调用的方法
publicvoidprintname(stringn ) {
name=n;
system.out.println (theemployeenameis : ) name );
}
私有集成;
隐私名称;
}
项目代码:
//*
*使用keyName筛选使用search作为查询条件的结果集
/
公共映射图(搜索,字符串密钥名称)。
Listentities=this.getBaseDao ().search ),DaoParam.SEARCH_OPTION_NORMAL );
Mapmap=newLinkedHashMap (;
从参数keyName中获取getName、getAge等get方法名称
string method name=' get ' keyname.substring(0,1 ).toUpperCase ) ) keyname.substring (1);
for(tentity:entities )
对象密钥=null;
try{
//getter方法不需要参数
方法方法=entity.getclass ().getmethod () )方法名称);
//反射调用方法
key=method.invoke(entity;
if(keyinstanceofbasepojo({
如果getter方法返回BasePojo类,则将该BasePojo的id设置为key
key () basePojo ) key ).getId );
}
映射. put (key,entity );
}catch(exceptione ) {
Logger.error(e,e );
}
}
实体=null;
returnmap;
}