import javax.xml.bind.Marshaller;
import java.lang.reflect.Field;
//监听生成xml文件过程
public class MarshallerListener extends Marshaller.Listener {
public static final String BLANK_CHAR = "";
@Override
public void beforeMarshal(Object source) {
super.beforeMarshal(source);
Field[] fields = source.getClass().getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
try {
System.out.println(f.getType() + f.getName());
if (f.getType() == String.class && f.get(source) == null) {
f.set(source, BLANK_CHAR);
}else if(!isBaseType(f)&& f.get(source) != null){
beforeMarshalClass(f.get(source));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
private void beforeMarshalClass(Object source) {
// TODO Auto-generated method stub
Field[] fields = source.getClass().getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
try {
if (f.getType() == String.class && f.get(source) == null) {
f.set(source, BLANK_CHAR);
}else if(!isBaseType(f) && f.get(source) != null){
System.out.println(f.getType()+f.getName());
beforeMarshalClass(f.get(source));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
/**
* 判断object是否为基本类型
* @param object
* @return
*/
public static boolean isBaseType(Field f) {
System.out.println(f.getType());
System.out.println(String.class);
System.out.println(f.getType() == String.class);
if (f.getType() == Integer.class ||
f.getType() == Byte.class ||
f.getType() == Long.class ||
f.getType() == Double.class ||
f.getType() == String.class ||
f.getType() == Float.class ||
f.getType() == Character.class ||
f.getType() == Short.class ||
f.getType() == Boolean.class) {
return true;
}
return false;
}
}