这是实现Writable ..的类
public class Test implements Writable {
List<AtomicWritable> atoms = new ArrayList<AtomicWritable>();
public void write(DataOutput out) throws IOException {
IntWritable size = new IntWritable(atoms.size());
size.write(out);
for (AtomicWritable atom : atoms)
atom.write(out);
}
public void readFields(DataInput in) throws IOException {
atoms.clear();
IntWritable size = new IntWritable();
size.readFields(in);
int n = size.get();
while(n-- > 0) {
AtomicWritable atom = new AtomicWritable();
atom.readFields(in);
atoms.add(atom);
}
}
}
如果能帮助我理解如何调用write和readFields方法,我将不胜感激。
基本上,在这种情况下,我无法理解如何构造Test对象。将对象写入DataOutput obj后,如何在DataInput对象中还原它。这听起来很愚蠢,但是对Hadoop来说是新手,并且已分配了一个使用Hadoop的项目。请帮忙。
谢谢!!!
最佳答案
Basically I m failing to understand how to construct
Test
object in this case.
是的,您错过了重点。如果您需要构造一个
Test
实例并填充atoms
,那么您需要向Test
添加一个构造函数:public Test(ArrayList<AtomicWritable> atoms) {
this.atoms = atoms;
}
或者您需要使用默认的构造函数并添加一个方法或 setter ,该方法或 setter 可以将项目添加到
atoms
或设置atoms
的值。后者实际上在Hadoop框架中很常见,具有默认构造函数和set
方法。参见,例如 Text.set
。您不会调用
readFields
和write
; Hadoop框架需要在map
和reduce
之间对输入和输出进行序列化和反序列化时,会为您执行此操作。
关于serialization - Hadoop中的序列化-可写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17228400/