如何使用Relfection注册接口回调? Android的

时间:2018-01-22 04:33:44

标签: android reflection

我有一个界面:

package com.testing.server;

public interface OnViewFoundListener{
     void onViewFound(String msg);
}

注册听众的类

   public class FindViewUtil {
               private static final List<OnViewFoundListener> 
       mOnViewFoundListeners = new ArrayList<>();

      public static void addViewListener(OnViewFoundListener onViewFoundListener) 
      {
        mOnViewFoundListeners.add(onViewFoundListener);
      }

     public static void notifyViewRendered() {
         mOnViewFoundListeners.get(0).onViewFound("Hello World");
     } 

    }

我希望能够使用addViewListener函数进行注册,并通过Reflection监听OnViewFoundListener的onViewFound回调。我怎样才能实现这个目标?

1 个答案:

答案 0 :(得分:0)

感谢Mike M,使用代理我可以设置回调。

OnViewFoundListener onFoundListner = java.lang.reflect.Proxy.newProxyInstance(
          OnViewFoundListener.class.getClassLoader(),
          new java.lang.Class[] { OnViewFoundListener.class },
          new java.lang.reflect.InvocationHandler() {
              @Override
              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                  //Do stuff here when callback is triggered
                  return null;
              }
          });

使用Reflection注册此实例回调:

public void registerUsingReflection(OnViewFoundListener onFoundListner){
              Class[] paramView = new Class[1];
              paramView[0] = Class.class;
              Class findViewUtil = null;
              try {
                  findViewUtil = Class.forName("com.example.FindViewUtil");
                  if (null != findViewUtil) {
                      Constructor constructor = findViewUtil.getDeclaredConstructor();
                      Object clazz = constructor.newInstance();
                      Method setListner = clazz.getClass().getDeclaredMethod("addViewListener", paramView);
                      setListner.invoke(clazz, onFoundListner);
                    return;
                  }
              } catch (ClassNotFoundException e1) {
                 e1.printStackTrace();
              } catch (IllegalAccessException e1) {
                  e1.printStackTrace();
              } catch (NoSuchMethodException e1) {
                  e1.printStackTrace();
              } catch (InvocationTargetException e1) {
                  e1.printStackTrace();
              } catch (InstantiationException e) {
                  e.printStackTrace();
              }
}