1、获取要反射的方法
获取反射方法时,有两个方法,getmethod 和 getdeclaredmethod。
class class { @callersensitive public method getmethod(string name, class<?>... parametertypes) throws nosuchmethodexception, securityexception { objects.requirenonnull(name); securitymanager sm = system.getsecuritymanager(); if (sm != null) { // 1. 检查方法权限 checkmemberaccess(sm, member.public, reflection.getcallerclass(), true); } // 2. 获取方法 method method = getmethod0(name, parametertypes); if (method == null) { throw new nosuchmethodexception(methodtostring(name, parametertypes)); } // 3. 返回方法的拷贝 return getreflectionfactory().copymethod(method); } @callersensitive public method getdeclaredmethod(string name, class<?>... parametertypes) throws nosuchmethodexception, securityexception { objects.requirenonnull(name); securitymanager sm = system.getsecuritymanager(); if (sm != null) { // 1. 检查方法是权限 checkmemberaccess(sm, member.declared, reflection.getcallerclass(), true); } // 2. 获取方法 method method = searchmethods(privategetdeclaredmethods(false), name, parametertypes); if (method == null) { throw new nosuchmethodexception(methodtostring(name, parametertypes)); } // 3. 返回方法的拷贝 return getreflectionfactory().copymethod(method); }}
2、在java5中,提供了for-each循环,从而简化了对数组和集合的循环。fore-each循环允许您遍历数组而不需要保留传统for循环中的索引,也不需要在使用迭代器时调用while循环中的hasnext方法和next方法来遍历集合。
double[] values = ...;for(double value : values) { // todo: 处理value} list<double> valuelist = ...;for(double value : valuelist) { // todo: 处理value}
3、得到当前方法的名字
<span style="font-family:arial;font-size:14px;">string methodname = thread.currentthread().getstacktrace()[1].getmethodname(); </span>
以上就是java中如何获取反射方法?的详细内容。