简体   繁体   English

如何使用反射实现回调?

[英]How to implement a callback using reflection?

I have this constructor in a jar: 我在罐子里有这个构造函数:

public ClientListFragment(String[] values, OnActionListener onActionListener)
{
    this.values = values;
    this.setOnActionListener(onActionListener);
}

This is the implementation of the abstract class OnActionListener: 这是抽象类OnActionListener的实现:

public abstract class OnActionListener {

    public abstract void onAction(int actonId);
}

In the main project, create an instance of this class, which is in a jar: 在主项目中,在一个jar中创建此类的实例:

 final String libPath = Environment.getExternalStorageDirectory() + "/myapi.jar";
           final File tmpDir = new File(libPath);

           final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader());
           final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("com.api.fragment.ClientListFragment");


//In this constructor, we inform an array of String and not know how to pass the callback of the abstract class
           Constructor constructor = classToLoad.getConstructor(new Class[]{String[].class});

//get a instance
           Object fragmentListClients = constructor.newInstance(items);

My question is: How do I report a callback to a loaded class via reflection in Java? 我的问题是:如何通过Java中的反射将回调报告给已加载的类? Ie how: 即如何:

onActionListener = new OnActionListener() {
            @Override
            public void onAction(int actonId) {

            }
        };
    Method onAction = classToLoad.getDeclaredMethod("onAction", int.class);
    onAction.invoke(fragmentListClients, 1);

Where fragmentListClients is the target object 1 is your actionId. 其中fragmentListClients是目标对象1是您的actionId。 You're using reflection to get a reference to the Method and invoking it. 您正在使用反射来获取对方法的引用并调用它。

You'd probably be better off creating an interface and using inheritance to implement and call your onAction method as that gets you type safety and avoids reflection for the method call which can be inefficient. 创建一个接口并使用继承来实现和调用onAction方法可能会更好,因为这可以使您键入安全,并避免对方法调用的反思,因为这样做可能会导致效率低下。

You must use Dynamic proxies to implement interfaces at run-time Please go through this link for more Info. 您必须在运行时使用动态代理来实现接口。请通过此链接获取更多信息。 http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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