简体   繁体   中英

Pass a java.lang.reflect.Method object to an interface

I'm trying to pass a java.lang.reflect.Method object to an interface. The problem is I don't know what is the best way to cast and how should I do it.

Look at example

interface IHandler<T> {
    void handle(T param);
}

interface IContentHandler {
    void process();
}

interface IManageContentHandler {
    IManageContentHandler handler(IHandler<IContentHandler> param);
    IManageContentHandler next();
}

class Foo implements IContentHandler {
    @Override
    public void process() {

    }
}

class Bar implements IManageContentHandler {
    @Override
    public IManageContentHandler handler(IHandler<IContentHandler> param) {
        return this;
    }

    @Override
    public IManageContentHandler next() {
        System.out.println("Next");
        return this;
    }
}

class Job {

    public static void doSomething01(IContentHandler foo) {
        foo.process();
        System.out.println("process 01");
    }

    public static void doSomething02(IContentHandler foo) {
        foo.process();
        System.out.println("process 02");
    }

    public static void doSomething03(IContentHandler foo) {
        foo.process();
        System.out.println("process 03");
    }

}

Now I want to pass a method to the handler. this code works fine.

public class App {

    public static void main(String[] args) {

        Bar bar = new Bar();    
        
        bar.handler(Job::doSomething01);

    }
}

But the problem is I don't know how many methods will be, and I prefer to do it dynamically So I tried another method.

public class App {

    public static void main(String[] args) {
    
        Bar bar = new Bar();
        Class cls = Job.class;
        Method[] methods = cls.getDeclaredMethods();
        
        for (Method item : methods) {
            // this one is not true
            // "item" is a Method type but I must pass a IHandler<IContentHandler>
            bar.handler(item);
        }

    }
}

the method handler() accepts an instance of interface IHandler<IContentHandler> as its argument, so you can not pass an instance of Method to it ( Method is a completely different class).

if you insist on passing all static methods of the class Job you can use lambda closure:

    for (Method item : methods) {
        //** WARNING **: you MUST check each item to be sure that its argument and return type are what you want!
        bar.handler(param -> {
            try {
                item.invoke(null, param);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        });
    }

but this does not seem like a good design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM