获取要反射的方法
获取反射方法时,有两个方法,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); }}
以上就是java中如何使用反射获取指定方法?的详细内容。