Cícero Moura Cícero Moura - 1 year ago 230
Android Question

How to implement a callback using reflection?

I have this constructor in a jar:

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

This is the implementation of the abstract class 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:

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?
Ie how:

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


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

Where fragmentListClients is the target object 1 is your 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download