vendredi 20 juillet 2018

How to create instance of any Data Class in Java

Could somebody help me with one problem. Try to create a method where correct Class instance will be created.

public static String build(String response, String jsonObjectName,Class<?> className, String ... fields) {

    JsonParser parser = new JsonParser();
    JsonObject jObject = parser.parse(response).getAsJsonObject();
    JsonArray jsonArray = jObject.getAsJsonArray(jsonObjectName);
    List<Import.Items> objects = new ArrayList<>();
    for (JsonElement jsonElement : jsonArray) {
        String jsonFields[] = new String[fields.length];
        for (int i = 0; i < jsonFields.length; i++) {
            jsonFields[i] = jsonElement.getAsJsonObject().get(fields[i]).getAsString();
        }
        objects.add(new Import.Items(jsonFields));
    }
    String jsonImportTrade = new Gson().toJson(new Import(objects));
    System.out.println(jsonImportTrade);
        return jsonImportTrade;
    }
}

Here I faced with a problem. I need to use correct Class:

List<Import.Items> objects = new ArrayList<>(); -- here
objects.add(new Import.Items(jsonFields)); -- here
String jsonImportTrade = new Gson().toJson(new Import(objects)); -- and here.

As far as I understand I need to use reflection for this but i can't understand how could i use it here. Could someone explain how this could be solved?





Aucun commentaire:

Enregistrer un commentaire