0

我有一个 Mapper 类的实现,它接受 Object 作为其中一个map(Object object)函数的参数。其余map(T t)函数接受整数或类等。

当我尝试传递一个 int 时,它会自动装箱为 Integer 并调用map(Object object)而不是map(Integer integer).

我对 Double Dispatch 做了一些研究,发现我可以使用访客模式。但这不适用于我的情况,因为我没有传递可以让它们实现接口的自定义对象accept()

上述方法接受每个对象。

当您有一个也接受 Object 的方法时,是否有针对 Java 对象进行双重调度的解决方案?

public BaseMatcher map(Object object) {
        return something();
    }

    public BaseMatcher map(Integer integer) {
        return somethingOther();
    }

    public BaseMatcher map(Class<? extends Exception> klass) {
        return somethingOtherOther();
    }

对这些 map() 函数的调用如下:foo(Object object) { mapper.map(object); }这导致map(Object object)被调用。

4

1 回答 1

2

编译器只知道你的对象是对象,即对象的实例。map(Object)被调用也是如此。

如果您的 map 方法需要根据传递的对象的类型做一些不同的事情,那么它应该获取对象的具体类型,并相应地采取行动(使用instanceofgetClass()或whataver)。

另一种选择确实是使用多态性。但要做到这一点,调用者必须提供 Mappable 的集合,而不仅仅是对象的集合:

private interface Mappable {
    BaseMatcher mapMe(Mapper mapper);
}

public class IntegerMappable {
    private final Integer value;

    public IntegerMappable(Integer value) {
        this.value = value;
    }

    @Override
    public BaseMatcher mapMe(Mapper mapper) {
        return mapper.map(this.value);
    }
}

当您想要映射对象时,您可以将它们包装到适当的 Mappable 中(或使用 lambda):

List<Mappable> mappables = new ArrayList<>();
mappables.add(new IntegerMappable(2));
mappables.add(new StringMappable("hello");
mappables.add(mapper -> mapper.map(42));
于 2016-07-02T09:08:39.763 回答