简体   繁体   中英

How do I get the class type of Object from HashMap<String, Object>?

I have 4 different Hashmaps with different class types for their value.

(Hashmap<String, Class1>, Hashmap<String, Class2>, Hashmap<String, Class3>, Hashmap<String, Class4>)

Each of these has a respective directory in the resources folder with a set of Json files. I want to deserialize all of the Json files within the directory as the correct class type and store them in the HashMap inputted as an argument.

Gson requires an input of the class type where I've written #OBJECTCLASS# to create an object. How can I obtain this from the HashMap inputted as the method argument?

//load a hashmap with the objects saved in its resource file
    public static void loadObjsFromDirectory(HashMap<String, Object> map, String directoryPath) {
        File[] files = new File(directoryPath).listFiles();

        //null safety
        if (files == null) {
            System.out.println(filePath + " is empty");
            return;
        }

        Gson gsonDeserializer = new Gson();
        //deserialize each json file and put the created object in its map
        for (File file : files) {
            //make sure the Json file is parsed correctly
            try {
                Object object = gsonDeserializer.fromJson(String.valueOf(file), #OBJECTCLASS#);
                map.put(file.getName(), object);
                System.out.println(file.getName() + " is loaded");
            } catch (JsonParseException e){
                System.out.println(file.getName() + "is incorrectly parsed");
            }
        }
    }

eg

public static void main(String[] args) throws Exception {
    HashMap<String, Class1> map1 = new HashMap<>();
    HashMap<String, Class2> map2 = new HashMap<>();

    Utils.loadObjsFromDirectory(map1, "directoryPath1");
    Utils.loadObjsFromDirectory(map2, "directoryPath2");
}

Should create all the files in directoryPath1 as Class1 objects and all the files in directoryPath2 as Class2 objects.

You could use com.google.gson.reflect.TypeToken .

A snippet of my code:

Map<String, Object> bodyMap = GSON.fromJson(request.body(), new TypeToken<Map<String, Object>>(){}.getType())

You can parameterise and mimic the Gson approach and pass in a Class parameter:

public static void <ExpectedType>loadObjsFromDirectory(Class<ExpectedType> expectedType, HashMap<String, ExpectedType> map, String directoryPath) {

//later
ExpectedType object = gsonDeserializer.fromJson(String.valueOf(file), expectedType);

ExpectedType is a type parameter that applies to the method declaration only. It is not a class that is defined anywhere in your code.

The calling code (main method) would become:

public static void main(String[] args) throws Exception {
    HashMap<String, Class1> map1 = new HashMap<>();
    HashMap<String, Class2> map2 = new HashMap<>();

    Utils.loadObjsFromDirectory(Class1.class, map1, "directoryPath1");
    Utils.loadObjsFromDirectory(Class2.class, map2, "directoryPath2");
}

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