Mixed Java Display Types

I am looking for a way to create a HashMap that maps to mixed types.

For example, the following will work in Python (note that Python dictis similar to Java HashMap):

d = dict()
d["str"] = "This is a string"
d["flt"] = 1.23
d["int"] = 5

and when accessing the d[x]corresponding type will be returned (string, float, int in this example).

In Java, I could work with HashMap<String, Object>, but I have no way to immediately indicate what type of each object is.

So instead, I'm trying to create a class MixedTypethat contains an object, but also its original type information, so that I can turn it off later. For instance:

public class MixedMap
    public static class MixedType
    {
        public Class<?> cls;
        public Object val;

        public MixedType(Class<?> c, Object v)
        {
            this.cls = c;
            this.val = v;
        }
    }

    public static void main(String args[])
    {   
        MixedType m1 = new MixedType(String.class, "This is a String");
        System.out.println((m1.cls)m1.val);
    }
}

Please note that this is what I am trying to do :-) since he is not currently compiling complaints about that m1 cannot be resolved to a type.

, : ? , , , , - .

.

+5
2

- m1.cls.cast(m1.val), Map<String, Object>. , โ€‹โ€‹ โ€‹โ€‹ , , - getClass() Object .

- String value = map.get("str") - , , .

Object value = map.get("str");
if (value instanceof String) {
  // do stringy things
}

- .

, , , . "" โ€‹โ€‹ - Map, Configuration, , Map, - , , .

+6

. generics . MixedKey, MixedMap. - :

public class MixedKey<T> {
    public final Class<T> cls;
    public final String key;

    public MixedKey(T cls, String key) {
        this.key = key;
        this.cls = cls;
    }

    // also implement equals and hashcode
}

.

public class MixedMap extends HashMap<MixedKey<?>,Object> {
    public <T> T putMixed(MixedKey<T> key, T value) {
        return key.cls.cast(put(key, value));
    }

    public <T> T getMixed(MixedKey<T> key) {
        return key.cls.cast(get(key));
    }
}

, - , , , :

MixedKey<Integer> keyForIntProperty
    = new MixedKey<Integer>(Integer.class, "keyForIntProperty");

// ...

String str = mixedMap.getMixed(keyForIntProperty); // compile-time error

.

String str = (String)map.get("keyForIntProperty"); // run-time error only
+2

All Articles