samedi 6 juillet 2019

"Casting" a method to a Consumer

I'm trying to make a HttpServer in Java that reads the methods from a single class to try and make my code automatically adapt to changes, instead of having to copy/paste setHandler calls for every path I want.

To do this, I decided to try making a holder class with a field that one could use to call a method, and I wrote down an initialization function that loops through all methods in a "module," and then fills in the field that accepts the method. The problem is, for simplicity's sake, I typed the field as a FunctionalInterface with the corresponding types, but the compiler refuses to implicitly convert. Is there some kind of function, or cast that I gotta do?

This is the class

public class WebHandler {
    private String path;
    private ContentType type;
    private TriConsumer<Request, HttpServletRequest, HttpServletResponse> handler;

    public WebHandler(String path, ContentType type, TriConsumer<Request, HttpServletRequest, HttpServletResponse> handler) {
        this.path = path;
        this.type = type;
        this.handler = handler;
    }
}

This is the line that fails to compile (method is just a Method from reflection)

WebHandler newHandler = new WebHandler(annotation.path(), annotation.type(), method);

This line is part of the for loop that finds handler methods. method is the handler method it found and is trying to make a WebHandler with it.

As expected, the compiler complains about incompatible types. incompatible types: java.lang.reflect.Method cannot be converted to org.frostbytes.smmjam.util.TriConsumer<types ommitted for length>

In the end, what I want to do is to be able to call the function repeatedly with no reflection overhead after I've looked it up.





Aucun commentaire:

Enregistrer un commentaire