繁体   English   中英

反射:使用接口创建类的对象

[英]Reflection: create object of class with interface

我正在尝试编写一种将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);
        }
    }

泛型将在这里帮助您安全地执行此操作:

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

如果您确定该类实现了所需的接口,请添加检查并进行强制转换:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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