Search code examples
javapythonisinstance

Which is the equivalent of "isinstance" (Python) for Java?


I have a program to generate requests to test Apis, the next part of the code reads a JSON to manage the info of the values later:

def recorre_llaves(self, dicc):
    campos = []
    for k in dicc.keys():
        if isinstance(dicc[k], dict):
            for e in self.recorre_llaves(dicc[k]):
                campos.append(e)
        elif isinstance(dicc[k], list):
            if isinstance(dicc[k][0], dict):
                for e in self.recorre_llaves(dicc[k][0]):
                    campos.append(e)
                pass
            else:
                campos.append(Campo(k, dicc[k][0]))
        else:
            campos.append(Campo(k, dicc[k]))
        pass
    return campos
    pass

The program iterates over the JSON and creates new objects with the key and the value. Now I need to do the same but using Java and I'm having problems with the method "isInstance()" I want to do something like:

import com.fasterxml.jackson.databind.ObjectMapper;    
HashMap <String, Object> response = mapper.readValue(request, HashMap.class);    
HashMap.get("KEY").isInstance();

But it doesn't works, Do you know a way to do the same with Java?


Solution

  • list in Python corresponds to List in Java (see the javadoc of java.util.List).
    And dict in Python corresponds to Map in Java (see the javadoc of java.util.Map).

    The Python function isinstance corresponds to the Java key-word instanceof.

    Hence the Python line

    if isinstance(dicc[k], dict):
    

    would be written in Java like this:

    if (dicc.get(k) instanceof List)