?
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * * <pre> * Title:反射工具类 * Description: 反射指定类的方法和Spring容器中Bean的方法 * </pre> * @author o_oand0_0 */ /* * 修改历史 * $log$ */ public class ClassCallUtil implements ApplicationContextAware{ private ApplicationContext applicationContext; /*** * 反射spring容器中Bean的方法 * @param beanName //要反射的bean名称(配置在Spring容器的Bean) * @param methodName //要反射的方法名 * @param parmsVaues //方法的参数数组 * @return */ public Object invkMtdOfSprBean(String beanName,String methodName,Object[]parmsValues) { try { Object owner=this.getApplicationContext().getBean(beanName); Class clazz=owner.getClass(); Class[]parmClass=null; if(parmsValues!=null&&parmsValues.length>0){ parmClass=new Class[parmsValues.length]; for(int i=0;i<parmsValues.length;i++){ parmClass[i]=parmsValues[i].getClass(); } } Method method=clazz.getMethod(methodName, parmClass); return method.invoke(owner, parmsValues); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); return null; } return null; } /*** * 反射普通Java类 * @param className //要反射的类全名 * @param methodName //要反射的方法名 * @param parmsVaues //方法的参数数组 * @return */ public Object invkMtdOfPlnClass(String className,String methodName,Object[]parmsValues) { try { Object owner=Class.forName(className); Class clazz=owner.getClass(); Class[]parmClass=null; if(parmsValues!=null&&parmsValues.length>0){ parmClass=new Class[parmsValues.length]; for(int i=0;i<parmsValues.length;i++){ parmClass[i]=parmsValues[i].getClass(); } } Method method=clazz.getMethod(methodName, parmClass); return method.invoke(owner, parmsValues); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }catch(Exception e){ return null; } return null; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public ApplicationContext getApplicationContext() { return applicationContext; } }
?
?
调用实例:
public static void main(String[] args) { ClassCallUtil db=new ClassCallUtil(); String id ="12"; byte[] bs =null; // testService是applicationContext.xml中配置的一个对象名,改对象对应的接口有个readPhoto(String id)方法 bs=( byte[] )db.invkMtdOfSprBean("testService", "readPhoto", new Object[]{id}); // ...... }
?
?