jeudi 1 octobre 2020

How do I choose action depending on type in this case?

Feel free to improve the title and to add tags. I did not know the terminology to use here.

I have classes like this:

abstract class A {
    void foo(Object obj) {
        pre();

        if(obj instanceof Map<String, String[]>) {
            methodA();
        } else if (obj instanceof Map<String, String>) {
            methodB();
        } else if (obj instanceof JSONObject) {
            ...

        post();
    }

    abstract protected void methodA();
    abstract protected void methodB();
}

class B extends A { /* Stuff */}

Note that I have two different maps. But let's focus on the first, Map<String, String[]>. The if statment did not compile, so I tried this:

interface MyMap extends Map<String, String[]> {}

and

if(obj instanceof MyMap) {

That compiled. However, this does not seem to work.

Map<String, String[]> map = new Hashtable<>();
B b = new B();
b.foo(map);

This makes the above if statement fail, so I tried this:

MyMap map = new Hashtable<>();

But then I get this:

incompatible types: cannot infer type arguments for java.util.Hashtable<>

and with

MyMap map = new Hashtable<String, String[]>();

I get this:

incompatible types: java.util.Hashtable<java.lang.String,java.lang.String[]> cannot be converted to MyMap

What I'm trying to achieve here is that previously, I had a separate method for each object. But I don't like the code duplication, because the pre() and post() are the same for all of them. How should I solve this?

Aucun commentaire:

Enregistrer un commentaire