清單22使用ExportableGenerator的程序
public class TestExportable {
public TestExportable() {
super();
}
public static void main(String[] args) {
Regular em=new Regular("Catherine","IBM","Software Engineer","82888288","BJ", new Date());
Employee vn1=new Vendor("Steve","IBM","PVC","8");
Employee vn2=new Vendor("Steve","IBM","PVC","8");
Employee ct=new Contractor("Joe","IBM");
Employee sup=new Supplemental("Linda","IBM","8");
em.addMemeber(vn1);
em.addMemeber(vn2);
em.addMemeber(ct);
em.addMemeber(sup);
PrintWriter ps;
try {
ps = new PrintWriter(new FileOutputStream(new File("C:\\test.output"),true));
ExportableGenerator eg=new TXTExportableGenerator(ps);
eg.genDoc(em,0);
eg.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
清單23 ExportableGenerator
public abstract class ExportableGenerator {
PrintWriter out = null;
public ExportableGenerator(PrintWriter out) {
super();
this.out = out;
}
public void genDoc(Employee e, int tagNum) {
Class employee = e.getClass();
Field[] fields = employee.getDeclaredFIElds();
outputFIEldHeader(out,e);
for (Field f : fIElds) {
if (f.isAnnotationPresent(Exportable.class)) {
if (f.getType() != ArrayList.class) {
for(int i=0; i<tagNum;i++){
out.print("***");
}
outputSimpleFIEld(out, f, e);
}else{
try {
ArrayList team=(ArrayList)f.get(e);
out.println("-----------------------------");
for(int i=0;i <team.size();i++){
Employee member=(Employee)team.get(i);
genDoc(member,tagNum+1);
out.println("-----------------------------");
}
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
}
}
}
outputFIEldFooter(out,e);
}
public void flush(){
out.flush();
out.close();
}
protected String value(FIEld f, Object obj) {
Class type = f.getType();
try {
if (type == String.class)
return (String) f.get(obj);
if (type == Date.class) {
return DateFormat.getDateInstance().format((Date)f.get(obj));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
return f.getName();
} catch (IllegalAccessException e) {
e.printStackTrace();
return f.getName();
}
return f.getName();
}
protected abstract void outputSimpleField(PrintWriter out, FIEld f,
Object obj);
protected abstract void outputFIEldHeader(PrintWriter out,Object e);
protected abstract void outputFIEldFooter(PrintWriter out,Object e);