mardi 24 mars 2015

Reflection: create object of class with interface

I am trying to write a generic method to insert json data into the database. I get the object (different classes) created. However, I can not pass it to the next method, because compiler says, it is not of type 'MyInterface', which the class implements. Is there a way to cast the obj to it's real class (dynamically evaluating the current class)? Or turn of compiler error checking for this method? Or any other idea?



public static int updateDBObjectJson(Uri uri, Class dbObject, String json) {
int changedEntries = 0;
if (json.length() > 5) {
try {
JSONArray jArr = new JSONArray(json);
for (int i = 0; i < jArr.length(); i++) { // no for each available
JSONObject jObj = jArr.optJSONObject(i);

Constructor ct = dbObject.getConstructor(JSONObject.class);
Object obj = ct.newInstance(jObj);

// update DB
--> does not compile: boolean changed = upsertEntry(uri, obj, false);
--> correct answer: boolean changed = upsertEntry(uri, (MyInterface) obj, false);
if (changed)
changedEntries++;
}
} catch (JSONException e) {
ILog.e("JSON Error: " + json);
} catch (Exception e) {
ILog.e(e);
}
}





Aucun commentaire:

Enregistrer un commentaire