【问题标题】:Retrieve specific field from an object of Map<String, Object>从 Map<String, Object> 的对象中检索特定字段
【发布时间】:2014-01-15 05:38:49
【问题描述】:

我需要有人帮助才能从地图中检索字段。

这是我的代码:

Private List<Job> allJobs;
public void getAllIds(Event e) {

   Map<String, Object> rs=null;

   for(Job j:allJobs) {

       // Contains key as 'data' and value as object (might be any class)
       rs=j.getVariable(id);

       // Here I need get the company id from the object of 'rs'
   }
}

这是我传递给Object的类结构之一:

class Server {
      UserContext userContext;
}

class UserContext {
      int companyId;
}

我需要从上面的rs 获取这个公司 ID。

如何在不将对象转换为类类型的情况下实现这一目标?

或者如果我们知道类名(如String),我可以将此对象类型转换为动态类类型吗?

【问题讨论】:

  • 您正在扩展 UserContext 并将其作为 Server 的属性??
  • 您需要详细说明您的问题。是 j.getVariable(id);返回一个 Map ?另外,这里的 companyId 是什么?地图是否有UserContext作为对象(地图中键值对的值)
  • Hrishikesh,感谢您的回复。雅 j.getVariable(id);返回一个 Map。在这种情况下,对象是“服务器”类的类型。并且服务器类具有 UserContext 属性,该属性具有 companyId 属性。

标签: java json generics dynamic-cast


【解决方案1】:

必须使用 Object 吗?你可以像这样添加一个接口:

interface Accessible<T> {
    T getValue();
}    

然后像这样对那些类使用它,可以存储在rs中:

class Server implements Accessible<Integer> {
    UserContext userContext;

    @Override
    public Integer getValue() {
        return userContext.getCompanyId();
    }
}

在你的方法中:

private List<Job> allJobs;
public void getAllIds(Event e) {
    Map<String, Accessible<Integer>> rs=null;

    for(Job j:allJobs) {
        rs=j.getVariable(id);
        int myCompanyId = rs.get("my_company").getValue();
    }
}

【讨论】:

  • 谢谢迈克尔,但这里是 j.getVariable(id);返回 map 类型,即这里的 Object 类型不仅是 Server 类,它可以是任何类类型(我的意思是动态转换为类到对象类型)。
  • 你能让 j.getVariable(id) 返回 Map 吗?
  • 不,我不这么认为,因为我有不同的课程
  • Lets take a look. You have different classes, which have different goals. But you want to handle them in a similar way, while getting some info from them. So thats 为什么我建议你使用一个接口,它应该由你的所有类实现,可以从 j.getVariable(id) 接收。换句话说,这将意味着“这些类是不同的,但它们都可以使用特定于类的逻辑来获取某些值”。
  • 这里我有不同的类,比如 Server 类,如果我通过实现 Accessible 接口在每个类中编写相同的 getValue 函数,然后从 getAllJobs(Event e) 调用它,它如何区分它从一个班级到另一个班级?
猜你喜欢
  • 1970-01-01
  • 2020-08-27
  • 2020-11-02
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
相关资源
最近更新 更多