Java反射:实现接口并传递给另一个类

我不确定Java是否可以实现,但我正在尝试实现一个在编译时不可用的接口**并将其作为该接口的对象传递给另一个类.假设我有一个界面,如:

public interface MyInterface {
    void onReceive(int i);
}

和另一类如:

public void MyClass {
    ArrayList<MyInterface> listenerList = new ArrayList<MyInterface>();

    public void add(MyInterface m) {
        listenerList.add(m);
    }
}

如果它们在编译时可用,我将使用它们:

blah = new MyInterface() {
    public void onReceive(int i) {
        System.out.println("BLAH");
    }
}

MyClass mc = new MyClass();
myClass.add(blah);

我想知道如果前两个类只在运行时可用,是否有办法编写与上面相同的代码.

提前致谢!

**我正在尝试使用Android的ROM中的框架库,但它是在dalvik字节码中,所以我不能用它来编译.

更新:这是我用来测试解决方案的一些示例代码:

文件a / IIMSListener.java

// Excerpt from decompiled class

public interface IIMSListener
{
    void onReceive(int p0, int p1/*, IMSParameter p2*/);
}

文件a / IMSRemoteListenerStub.java

// Excerpt from decompiled class

import java.util.concurrent.*;
import java.util.*;

public class IMSRemoteListenerStub
{
    public List<IIMSListener> mListenerList = new CopyOnWriteArrayList<IIMSListener>();

    public boolean addListener(final IIMSListener iimsListener) {
        if (iimsListener != null && !this.mListenerList.contains(iimsListener)) {
            this.mListenerList.add(iimsListener);
            return true;
        }
        return false;
    }

    public boolean removeListener(final IIMSListener iimsListener) {
        if (iimsListener != null && this.mListenerList.contains(iimsListener)) {
            this.mListenerList.remove(iimsListener);
            return true;
        }
        return false;
    }
}

文件b / test.java

import java.lang.reflect.;
import java.util.;

public class test {
  public static void main(String[] args) throws IllegalAccessException,
                                                IllegalArgumentException,
                                                InvocationTargetException,
                                                NoSuchMethodException,
                                                SecurityException,
                                                ClassNotFoundException {

    // Implement interface
    Class<?> IIMSListener = Class.forName("IIMSListener");

    Object listenerInstance = Proxy.newProxyInstance(IIMSListener.getClassLoader(), new Class<?>[]{IIMSListener}, new InvocationHandler() {
      @Override
      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(method.getName().equals("onReceive")){
          System.out.println("ARGS: " + (Integer)args[0] + ", " + (Integer)args[1]);
          return 1;
        }
        else return -1;
      }
    }); 

    // Test
    Method onReceive = listenerInstance.getClass().getDeclaredMethod("onReceive", new Class[] { int.class, int.class });
    onReceive.invoke(listenerInstance, new Object[] { 1, 2 });

    try {
      // Pass to another class
      Class IMSRemoteListenerStub = Class.forName("IMSRemoteListenerStub");
      Constructor ctor = IMSRemoteListenerStub.getConstructor();
      Object stubInstance = ctor.newInstance(new Object[] {});
      Method addListener = stubInstance.getClass().getDeclaredMethod("addListener", new Class[] { IIMSListener });
      addListener.invoke(stubInstance, new Object[] { listenerInstance });

      // Test
      Field mListenerList = IMSRemoteListenerStub.getField("mListenerList");
      List<?> list = (List<?>)mListenerList.get(stubInstance);
      onReceive.invoke(list.get(0), new Object[] { 3, 4 });
    }
    catch (InstantiationException e) {}
    catch (NoSuchFieldException e) {}
  }
}

执行:

$cd b
$CLASSPATH=".:../a" java test
ARGS: 1, 2
ARGS: 3, 4

解决方法:

如果它将是相同的接口,那么使用Dynamic Proxies

//Loading the class at runtime
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
    Class<?> someInterface = Class.forName("SomeInterface");

    Object instance = Proxy.newProxyInstance(someInterface.getClassLoader(), new Class<?>[]{someInterface}, new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            //Handle the invocations
            if(method.getName().equals("someMethod")){
                return 1;
            }
            else return -1;
        }
    }); 
    System.out.println(instance.getClass().getDeclaredMethod("someMethod", (Class<?>[])null).invoke(instance, new Object[]{}));
}
上一篇:java – 在Android中实现类似Spring的包扫描


下一篇:数据库驱动连接问题