Java – inheritance aware class for mapping to replace the ‘instanceof’ series

I'm looking for some magical class map utilities that give a type and return the value associated with that type or its closest supertype This is a replacement statement or something

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

I have read the answer of avoiding instance of in Java, which puts forward many patterns, especially visitor pattern However, since the goal is to return a simple value, implementing visitors seems to be overkill

Unfortunately, the new JDK class classvalue is also ineligible because it does not check for supertypes

I want to check whether this utility exists in any well-known library before I launch it myself The implementation should be thread safe and want to have a lower number of values inserted than the linear cost w.r.t

Solution

Maps can be made If you want class inheritance, you need to go up

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);
    }
}

This is useful for int.class, etc

If there is a relationship between value and class:

public <T> T getValue(Class<T> clazz) {
    Object value = map.get(clazz);
    return clazz.cast(value);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>