java - 是否可以用 Java 编写通用多路复用器?

标签 java reflection observer-pattern

我有很多使用 setListener 方法注册的监听器,而不是 addListener。因此,为了允许多个监听器注册到一个对象,我必须使用多路复用器。这很好,但现在我必须为我拥有的每个监听器接口(interface)创建一个多路复用器。所以我的问题是:是否可以按照以下代码的要求实现 Mux.create()?

AppleListener appleListener1 = new AppleProcessorA();
AppleListener appleListener2 = new AppleProcessorB();
AppleListener appleListenerMux = Mux.create(appleListener1, appleListener2);
Apple apple = new Apple();
apple.setListener(appleListenerMux);

OrangeListener orangeListener1 = new OrangeProcessorA();
OrangeListener orangeListener2 = new OrangeProcessorB();
OrangeListener orangeListenerMux = Mux.create(orangeListener1, orangeListener2);
Orange apple = new Orange();
orange.setListener(orangeListenerMux);

class Mux {
   public static <T> T create(T... outputs) { }
}

我想这也许可以通过反射来实现。有什么理由使用反射不是一个好主意吗? (想到性能)

最佳答案

可以使用动态 Proxy .

最简单的方法是将所需接口(interface)作为第一个参数传递给您的 Mux.create() 调用。否则,您将不得不使用反射来尝试从提供的所有具体监听器实例中猜测所需的接口(interface)(很难确定是否所有监听器对象都实现了多个公共(public)接口(interface))。

这是它的缩写:

public class Mux {

    /**
     * @param targetInterface
     *            the interface to create a proxy for
     * @param instances
     *            the concrete instances to delegate to
     * @return a proxy that'll delegate to all the arguments
     */
    @SuppressWarnings("unchecked")
    public static <T> T create(Class<T> targetInterface, final T... instances) {
        ClassLoader classLoader = targetInterface.getClassLoader();
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method m, Object[] args)
                    throws Throwable {
                for (T instance : instances) {
                    m.invoke(instance, args);
                }
                return null;
            }
        };
        return (T) Proxy.newProxyInstance(classLoader,
                new Class<?>[] { targetInterface }, handler);
    }
}

例如,您将按如下方式使用:

Apple apple = new Apple();
AppleListener l1 = new AppleListenerA();
AppleListener l2 = new AppleListenerB();
apple.setListener(Mux.create(AppleListener.class, l1, l2));
apple.doSomething(); // will notify all listeners

这通过简单地创建动态 Proxy 来实现转换为目标类型 T。该代理使用 InvocationHandler仅将所有方法调用委托(delegate)给给定具体实例的代理。

请注意,虽然通常我会尽可能完成所有参数和局部变量,但在这种情况下我只完成了 T...instances 以强调如果 instances 不是 final,然后在匿名内部类中引用它是不允许的(你会得到一个“不能在不同方法中定义的内部类中引用非最终变量args” ).

另请注意,上面假设实际方法调用不返回任何有意义(或有用)的值,因此 handler 也为所有方法调用返回 null .如果您想要收集返回值并以有意义的方式返回这些值,则需要添加更多代码。


或者,可以检查所有给定的实例以确定它们都实现的公共(public)接口(interface),并将所有这些传递给newProxyInstance()。这使得 Mux.create() 使用起来更加方便,但失去了对其行为的一些控制。

/**
 * @param instances
 *            the arguments
 * @return a proxy that'll delegate to all the arguments
 */
@SuppressWarnings("unchecked")
public static <T> T create(final T... instances) {

    // Inspect common interfaces
    final Set<Class<?>> commonInterfaces = new HashSet<Class<?>>();
    commonInterfaces.addAll(Arrays.asList(instances[0].getClass()
            .getInterfaces()));

    // Or skip instances[0]
    for (final T instance : instances) {
        commonInterfaces.retainAll(Arrays.asList(instance.getClass()
                .getInterfaces()));
    }

    // Or use ClassLoader.getSystemClassLoader();
    final ClassLoader classLoader = instances[0].getClass().getClassLoader();

    // magic
    final InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(final Object proxy, final Method m, final Object[] args)
                throws Throwable {
            for (final T instance : instances) {
                m.invoke(instance, args);
            }
            return null;
        }
    };

    final Class<?>[] targetInterfaces = commonInterfaces
            .toArray(new Class<?>[commonInterfaces.size()]);
    return (T) Proxy.newProxyInstance(classLoader, targetInterfaces,
            handler);
}

关于java - 是否可以用 Java 编写通用多路复用器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15872006/

相关文章:

javascript - 如何从 JavaScript 文件中获取方法名称

promise - 在 Angular 2 中为模拟数据创建 Observable

java - 比较 Java 中公共(public)元素列表的更快方法?

java - 在Java中将字符串拆分为两个字符

java - 如何禁用更改数组内的变量?

java - 通过反射在运行时获取通用字段类型

java - 如何在 Java 中查找重载的方法?

java - 这行代码产生了什么?

oop - 为什么观察者模式应该被弃用?

java - 计算Excel工作表一列中的行数(提供Java代码)