反思:用界面创建类的对象

时间:2015-03-24 12:39:06

标签: java reflection

我正在尝试编写一个将json数据插入数据库的通用方法。我得到了创建的对象(不同的类)。但是,我不能将它传递给下一个方法,因为编译器说,它不是类实现的类型'MyInterface'。有没有办法将obj转换为它的真实类(动态评估当前类)?或者转向此方法的编译器错误检查?还是其他任何想法?

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);
        }
    }

2 个答案:

答案 0 :(得分:2)

泛型将帮助这里安全地进行输入:

public static int updateDBObjectJson(..., Class<? extends MyInterface> dbObject, ...) {
    ...
    JSONObject jObj = jArr.optJSONObject(i);

    Constructor<? extends MyInterface> ct = dbObject.getConstructor(JSONObject.class);
    MyInterface obj = ct.newInstance(jObj);
    ...
    boolean changed = upsertEntry(uri, obj, false);
    ...
}

答案 1 :(得分:1)

如果您确定该类实现了您需要的接口,请添加一个检查和强制转换:

Object tmp = ct.newInstance(jObj);
if (!(tmp instanceof MyInterface)) {
    // Throw an exception that you did not expect this to happen
}
// This will succeed because of the check above
MyInterface obj = (MyInterface)tmp;
// update DB
boolean changed = upsertEntry(uri, obj, false);