1 2 3 4 package net.nutch.io; 5 6 import java.io.*; 7 import java.lang.reflect.Array ; 8 9 10 public class ArrayWritable implements Writable { 11 private Class valueClass; 12 private Writable[] values; 13 14 public ArrayWritable(Class valueClass) { 15 this.valueClass = valueClass; 16 } 17 18 public ArrayWritable(Class valueClass, Writable[] values) { 19 this(valueClass); 20 this.values = values; 21 } 22 23 public ArrayWritable(String [] strings) { 24 this(UTF8.class, new Writable[strings.length]); 25 for (int i = 0; i < strings.length; i++) { 26 values[i] = new UTF8(strings[i]); 27 } 28 } 29 30 public String [] toStrings() { 31 String [] strings = new String [values.length]; 32 for (int i = 0; i < values.length; i++) { 33 strings[i] = values[i].toString(); 34 } 35 return strings; 36 } 37 38 public Object toArray() { 39 Object result = Array.newInstance(valueClass, values.length); 40 for (int i = 0; i < values.length; i++) { 41 Array.set(result, i, values[i]); 42 } 43 return result; 44 } 45 46 public void set(Writable[] values) { this.values = values; } 47 48 public Writable[] get() { return values; } 49 50 public void readFields(DataInput in) throws IOException { 51 values = new Writable[in.readInt()]; for (int i = 0; i < values.length; i++) { 53 Writable value; try { 55 value = (Writable)valueClass.newInstance(); 56 } catch (InstantiationException e) { 57 throw new RuntimeException (e.toString()); 58 } catch (IllegalAccessException e) { 59 throw new RuntimeException (e.toString()); 60 } 61 value.readFields(in); values[i] = value; } 64 } 65 66 public void write(DataOutput out) throws IOException { 67 out.writeInt(values.length); for (int i = 0; i < values.length; i++) { 69 values[i].write(out); 70 } 71 } 72 73 } 74 75 | Popular Tags |