带有构造函数newInstance的java.lang.NoSuchMethodException

时间:2012-09-13 11:12:19

标签: java web front-controller

我目前正在使用Java开发一些web开发项目,我已经实现了一个前端控制器,该工作是根据路径实例化新控制器。

那么当用户正在运行时?q = user / login ex。前端控制器应该实现UserController,我正在尝试使用这段代码。

    String q = request.getParameter("q");

    try {
        String[] page = q.split("/");
        // Make first char upper, to match class name conventions.
        page[0] = (page[0].substring(0, 1).toUpperCase() + page[0].substring(1).toLowerCase()).trim();

      Class contDes = Class.forName("dk.elvar.rocks." + page[0]+ "Controller");
      Constructor co = contDes.getConstructor();
      co.newInstance(request, response, page);

这导致

java.lang.NoSuchMethodException: dk.elvar.rocks.UserController.<init>()
at java.lang.Class.getConstructor0(Class.java:2706)
at java.lang.Class.getConstructor(Class.java:1657)
at dk.elvar.rocks.FrontController.doGet(FrontController.java:35)

我已经尝试在google上查找了,并且知道在加载对象中声明构造函数,使该类公开,已经存在错误。

UserController中:

public class UserController extends HttpServlet  {

private final String USERNAME = "Martin";
private final String PASSWORD = "David";

    private static final long serialVersionUID = 1L;
HttpServletRequest request;  
HttpServletResponse response;

public UserController(HttpServletRequest request, HttpServletResponse response, String[] action)  {
    this.request = request;
    this.response = response;

    if(action[1].equalsIgnoreCase("login")) {
        this.renderLoginAction();
    }
    if(action[1].equalsIgnoreCase("val-login")) {
        this.validateLoginAction();
    }
}

2 个答案:

答案 0 :(得分:14)

您可能会遇到此异常,因为该类没有默认构造函数。您可以通过将参数传递给getConstructor方法来获取带参数的构造函数:

Constructor co = contDes.getConstructor(
                HttpServletRequest.class, 
                HttpServletResponse.class, 
                String[].class);
co.newInstance(request, response, page);

答案 1 :(得分:0)

通常不建议使用其他默认构造函数,因为web.xml或struts-config.xml用于使用反射来实例化servlet。

如果你想获得除默认构造函数之外的类的实例,

Class userController = Class.forName("<packages.>UserController");
Constructor userControllerConstructor = userController.class.getConstructor(HttpServletRequest.class, HttpServletResponse.class, String[].class);
UserController userControllerObj = (UserController)constructor.newInstance(request,response, action);