博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java反射创建带构造参数的类 并执行方法
阅读量:6884 次
发布时间:2019-06-27

本文共 786 字,大约阅读时间需要 2 分钟。

  hot3.png

部分代码

public void go(ServletRequest request,ServletResponse response){		String methodName = "index";//方法名		String className = "indexAction";//类名		try{			Class
 action = Class.forName(className); //参数列表 Class
[] parameterTypes={ServletRequest.class,ServletResponse.class}; //获取参数对应的构造方法 Constructor
 constructor=action.getConstructor(parameterTypes);  //参数 Object[] parameters={request,response};   //获取方法 Method method = action.getMethod(methodName); //上面的方法针对public method 若目标是private method 则使用此种 //Method method = action.getDeclaredMethod(methodName); //method.setAccessible(true); method.invoke(constructor.newInstance(parameters)); } catch(Exception e){ e.printStackTrace(); }}

转载于:https://my.oschina.net/sgmder/blog/644551

你可能感兴趣的文章