简体   繁体   中英

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?

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)

instanceof returns a boolean

Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM