【问题标题】:How to create a callback using reflection in android?如何在android中使用反射创建回调?
【发布时间】:2018-12-26 02:03:37
【问题描述】:

我正在尝试使用反射访问方法,其中一个参数是回调。回调类型是不同类类型的通用接口。这些类是@SystemApi,可以通过反射访问。 Here 是我正在使用上述说法的班级。

下面是我的示例代码:

 String sClassName = "android.telephony.euicc.EuiccCardManager";
 Class classToInvestigate = Class.forName(sClassName);
 Class interfaceclass = classToInvestigate.getClasses()[0]; //android.telephony.euicc.EuiccCardManager.ResultCallback

 Method getallprofiles = classToInvestigate.getDeclaredMethod("requestAllProfiles", String.class,Executor.class, interfaceclass);
 getallprofiles.invoke(null,getEid(), AsyncTask.THREAD_POOL_EXECUTOR,null);

在上面的 invoke 签名作为最后一个参数中,我需要传递使用反射创建的回调,它与下面的回调示例等效或相似。

ResultCallback<EuiccProfileInfo[]> callback =
new ResultCallback<EuiccProfileInfo[]>() {
@Override
public void onComplete(int resultCode, EuiccProfileInfo[] result) { }
};
  • 上面的ResultCallback接口可以在我上面提供的同一个类链接和上面interfaceclass字段的同一个实例中找到。
  • EuiccProfileInfo 是另一个需要从反射访问的类,因为它是@SystemApi

我已经失败/卡住了用反射翻译上述回调逻辑。任何人都可以帮助我吗?

【问题讨论】:

  • @GennadiiSaprykin 是的,但在我的情况下,接口本身我需要进行反射。
  • 我的回答有帮助吗?还是你还需要这里的东西?

标签: java android reflection android-reflection


【解决方案1】:

看来你需要创建一个代理类:

// 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);
    }
}

但是如果你真的需要使用这样的东西——你做错事的可能性很大,你不能只添加对那个项目的依赖吗?但是你也不应该依赖系统类。

【讨论】:

  • 感谢您的回答..我将此作为基本想法来满足我的要求。 Proxy.newProxyInstance(interfaceclass.getClassLoader(), new Class[]{interfaceclass}, new ProxyListener());公共类 ProxyListener 实现 java.lang.reflect.InvocationHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ProxyListener.class); @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { return null; }}
  • Callback 在您的示例中表示您要实现的隐藏接口,对吗?您将通过Class&lt;?&gt; cCallback = Class.for("...") 获得。但是,如果您没有类型本身,您应该如何进行转换。如果您的意思是像在您的示例中那样自己声明隐藏接口,那么返回的代理仍然为空。
  • @phoebus OP 想要使用反射将这个回调传递给其他方法 - 所以他只需要一个 Object 我使用真实类型只是为了展示工作示例。如果需要,您也可以通过反射调用此方法。
  • 我创建了另一个问题,以便您了解我想要实现的目标以及我想如何使用它:stackoverflow.com/questions/51659917/…
  • @phoebus 我修改了我的答案,因此它不直接引用该示例回调类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
相关资源
最近更新 更多