继承感知类到值映射以替换`instanceof`系列 [英] Inheritance-aware class to value map to replace series of `instanceof`

查看:119
本文介绍了继承感知类到值映射以替换`instanceof`系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些神奇的 Map -like实用程序,在给定类型的情况下,返回与该类型或其最接近的超类型相关联的值。这是替换语句,如

I am looking for some magical Map-like utility that, given a type, return the value associated with the type or its closest super-type. This is to replace statements like

if (... instanceof A) return valueA;
else if (... instanceof B) return valueB;
...

我已经阅读了在Java中使用instanceof ,它提出了许多模式,特别是访问者模式。但是,由于目标是返回一个简单的值,实现访问者似乎是一种矫枉过正。

I have read the answers to Avoiding instanceof in Java, which suggested a number of patterns, in particular, the Visitor pattern. However, since the goal is to return a simple value, implementing the visitors seems to be an overkill.

不幸的是,新的JDK类 ClassValue 没有资格,因为它不会检查超类型。

Unfortunately, the new JDK class ClassValue also don't qualify as it does not check super-types.

我只是想在我自己推出之前检查这个实用程序是否存在于任何知名库中。实现应该是线程安全的,并且希望具有低于线性成本w.r.t.插入的值的数量。

I just want to check if such utility exists in any well-known library before I roll my own. The implementation should be thread-safe and hopefully has les than linear cost w.r.t. the number of values inserted.

推荐答案

地图可以。如果你想要类继承,你需要向上走。

A map will do. If you want class inheritance, you'll need to walk upwards.

private final Map<Class<?>, Object> map = HashMap<>();

public void register(Class<?> clazz, Object value) {
    map.put(clazz, value);
}

public Object getValue(Class<?> clazz) {
    if (clazz == null) {
        return null;
    }
    Object value = map.get(clazz);
    if (value == null) {
        clazz = clazz.getSuperclass(); // May be null.
        return getValue(clazz);
    }
}

这对很有帮助int.class etcetera。

This will do nicely for int.class etcetera.

如果值和类之间存在关系:

If there exists a relation between value and class:

public <T> T getValue(Class<T> clazz) {
    Object value = map.get(clazz);
    return clazz.cast(value);
}

这篇关于继承感知类到值映射以替换`instanceof`系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆