javananohttpd

Add arguments to RouterNanoHTTPD Handler


I'm using NanoHTTPD's RouterNanoHTTPD to add route mappings.

Calling addRoute(String uri, Class<?> handler, Object ... params) does not call the parameterized constructor to instantiate an object of the Class<?> handler. Has anyone been able to do this?

The problem is exactly the same as posted on this Github Issue of the NanoHTTPD.

public class SoapServer extends RouterNanoHTTPD {

    @Override
    public void addMappings() {
        super.addMappings();

        // works fine when there are no parameters passed
        addRoute("/onvif/device_service", DeviceServiceHandler.class);

        // MediaServiceHandler instantiated with empty constructor;
        // it doesn't create the class with these arguments in the constructor
        addRoute("/onvif/media_service", MediaServiceHandler.class,
            systemServices, userRepository, authenticators);
}

Solution

  • Was able to do so by cloning and changing the part of the library where object instantiation is happening.

    Instead of

    Object object = handler.newInstance();
    

    I have re-written this part to :

    Constructor<?> constructor = handler.getDeclaredConstructors()[0];
    constructor.setAccessible(true);
    Object object = constructor.newInstance(initParameter);
    

    This now calls the paramaterized constructor. Marking as solved for now, but not sure if this is the right way or if the creators of the library specifically didn't want it to be done this way.