问题
I am currently working on some web dev project in Java, i have implemented a frontcontroller, which job is to instantiate new controllers, depending on the path.
So when the user is running ?q=user/login ex. the front controller should instatiate the UserController, that i am trying to do with this piece of code.
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);
This results in a
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)
I've tryed to look it up at google, and bugs as, declaring a constructor in loaded object, make the class public, is already there.
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();
}
}
回答1:
You probably get this exception because that class does not have a default constructor. You can get a constructor with parameters by passing them to the getConstructor
method:
Constructor co = contDes.getConstructor(
HttpServletRequest.class,
HttpServletResponse.class,
String[].class);
co.newInstance(request, response, page);
回答2:
Generally its not recommended to use other then default constructor, as web.xml or struts-config.xml uses to instantiate the servlet using reflection.
If you want to get instance of your class other than default constructor,
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);
来源:https://stackoverflow.com/questions/12404963/java-lang-nosuchmethodexception-with-constructor-newinstance