我想使用GenericWritable在map-reduce流中实现同一键的不同值类型。例如,我为不同的值类型创建了两个用户定义的类,这是我的用户定义的值类之一:

public user_def_Value1 extends writableComparable<user_def_Value1> {
       private var1;
       private var2;
       ......
       public void setAsCopy(user_def_Value1 other) {
              var1.set(other.var1);
              var2.set(other.var2);
       }
       ......
}

然后,我使用GenericWritable进行两个用户定义的值类作为映射器的输出值。这是我的GenericWritable实现
public class GenericValue extends GenericWritable  {

    private static Class<? extends Writable>[] CLASSES = null;

    static {
        CLASSES = (Class<? extends Writable>[]) new Class[] {
            user_def_Value1.class,
            user_def_Value2.class
        };
    }

    //this empty initialize is required by hadoop
    public GraphCleanGenericValue() {
    }

    public GraphCleanGenericValue(Writable instance) {
        set(instance);
    }

    @Override
    protected Class<? extends Writable>[] getTypes() {
        return CLASSES;
    }

    @Override
    public String toString() {
        return get().toString();
    }
}

我的问题是在reducer方法中,当我使用values.next()获取通用值时,如何将该通用值转换为用户定义的类实例。这是我关于reducer()的实现,但是我不确定它是否安全。
public void reduce(key, Iterator<GenericValue> values,
                OutputCollector<outputKey, outputValue> output, Reporter reporter) throws IOException {
            user_def_Value1 temp = new user_def_Value1();
            temp.setAsCopy((user_def_Value1) values.next().get());
            ......
        }

最佳答案

您可以使用instanceof
例如:

Writable value = values.next().get();
if (value instanceof SomeClassName) {
    // do something;
}
else if (value instanceof AnotherClassName) {
    // do something;
}

10-08 17:31