How to create a callback using reflection in android?

前端 未结 1 1871
感情败类
感情败类 2021-01-21 16:33

I am trying to access a method using reflection and one of the parameter is a callback. The callback type is generic interface of different class type. These classes are @

1条回答
  •  梦毁少年i
    2021-01-21 16:43

    Seems that you need to create a proxy class:

    // that class you don't have access too. imagine that it is not here, it is just to show example signature of method we want to run.
    interface Callback {
        void run();
    }
    
    public static void main(String[] args) throws Exception {
        Class callbackClass = Class.forName("package.Callback");
        Callback callback = Proxy.newProxyInstance(Main.class.getClassLoader(), new Class[]{callbackClass}, new CallbackInvocationHandler(() -> {
            System.out.println("callback");
        }));
        callbackClass.getMethod("run").invoke(callback); // works!
    }
    
    static class CallbackInvocationHandler implements InvocationHandler {
        private final Runnable myCallback;
    
        CallbackInvocationHandler(Runnable myCallback) {
            this.myCallback = myCallback;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("toString") && (method.getParameterCount() == 0)) {
                // just random implementation
                return proxy.getClass() + "@" + Integer.toHexString(System.identityHashCode(proxy));
            }
            if (method.getName().equals("hashCode") && (method.getParameterCount() == 0)) {
                return System.identityHashCode(proxy);
            }
            if (method.getName().equals("equals") && (method.getParameterCount() == 1) && (method.getParameterTypes()[0] == Object.class)) {
                return proxy == args[0];
            }
            if (method.getName().equals("run") && (method.getParameterCount() == 0)) {
                // do what you want.
                myCallback.run();
                return null;
            }
            throw new IllegalStateException("Method not implemented: " + method);
        }
    }
    

    But if you really need to use something like that - there are huge chances you are doing something wrong, can't you just add dependency on that project? But you should not depend on system classes too.

    0 讨论(0)
提交回复
热议问题