2

我有一个 IMAP,其键是 a String,值是ArrayList. 我需要EntryProcessor在这张地图的一个键上运行。另请注意,这Employee是一个 POJO 实现Serializable接口的 POJO。

当我执行下面给出的代码时,代码会打印“为什么这样!” 我得到了ClassCastException其中提到的java.util.ArrayList不能用Employeesprocess()ListValueEntryProcessor转换的内容。

Q1。我了解到我需要为我的类型 ( Employees) 添加自定义序列化程序,以便可以将其序列化为Employees对象而不是ArrayList对象。我想知道为什么必须为内置类型添加“自定义序列化程序”,例如ArrayList其项目也被标记Serializable

public class Employees extends ArrayList implements Serializable
{

    private static final long serialVersionUID = 1L;

   /**
   Constructs a new employees object
   */
   public Employees()
   {
      super();
   }
}

HazelcastInstance hazelcastInstance = HazelcastHelper.getHazelcastInstance();
IMap<String, Employees> empMap = hazelcastInstance.getMap("employeesMap");

Employees empList = new Employees();
Employee employee = new Employee();
empList.add(employee);
empMap.put("companyId", employees);
empMap.executeOnKey("companyId", new IncSalaryEntryProcessor()); 

public static class ListValueEntryProcessor extends AbstractEntryProcessor<String, Employees>
{

    private static final long serialVersionUID = 1L;

    @Override
    public Object process(Entry<String, Employees> arg0) 
    {
        if(! (arg0.getValue() instanceof Employees))
        {
            System.out.println("Why so !");
        }
        // ClassCastException thrown here.
        Employees empList = arg0.getValue();
        return true;
    }

}
4

1 回答 1

4

这是我们这边的一个错误。我创建了一个错误报告:

https://github.com/hazelcast/hazelcast/issues/6455

以下代码暂时应该可以解决您的问题:

public class Main  {

public static void main(String[] args){
    HazelcastInstance hz = Hazelcast.newHazelcastInstance();
    IMap<String,Employees> map = hz.getMap("foo");
    map.put("1", new Employees());

    Employees employees = map.get("1");
    System.out.println(employees);
}

static class Employees extends ArrayList implements DataSerializable {
    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        out.writeInt(size());
        for(Object item: this){
            out.writeObject(item);
        }
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        int size = in.readInt();
        for(int k=0;k<size;k++){
            add(in.readObject());
        }
    }
}

}

于 2015-10-14T09:49:04.370 回答