Y
yysun
Unregistered / Unconfirmed
GUEST, unregistred user!
import java.lang.reflect.*;
public class Base {
public String toString() {
Class cls = this.getClass();
String tagname = cls.getName();
String xml = "<"+ tagname + ">";
Field fieldlist[] = cls.getDeclaredFields();
for (int i = 0;
i < fieldlist.length;
i++) {
Field fld = fieldlist;
String fieldname = fld.getName();
String ch1 = fieldname.substring(0,1).toUpperCase();
String methodname = "get" + ch1 + fieldname.substring(1);
try {
Method method = cls.getMethod(methodname, null);
Object retobj = method.invoke(this, null);
boolean ok = true;
if (retobj == null) {
ok = false;
}
else
if (fld.getType().getName()=="int") {
if (((Integer)retobj).intValue()<=0) ok = false;
}
if (ok) xml += "<" + fieldname + ">" + retobj + "</" + fieldname + ">";
}
catch(Exception ex) {
}
}
xml += "</"+ tagname + ">";
return xml;
}
}
例如,可以定义您的 JavaBean 为上述 Base 类的子类
public class MyBean extends Base {
private int id;
public int getId() { return id;
}
public void setId(int v) { id = v;}
public MyBean () {}
}
创建这个 Bean,赋值后就是输出 XML
MyBean mb = new MyBean();
mb.setId(100);
System.out.println(mb.toString());
结果是:
<MyBean><id>100</id></MyBean>
欢迎您试试更加复杂的 Java Bean。
public class Base {
public String toString() {
Class cls = this.getClass();
String tagname = cls.getName();
String xml = "<"+ tagname + ">";
Field fieldlist[] = cls.getDeclaredFields();
for (int i = 0;
i < fieldlist.length;
i++) {
Field fld = fieldlist;
String fieldname = fld.getName();
String ch1 = fieldname.substring(0,1).toUpperCase();
String methodname = "get" + ch1 + fieldname.substring(1);
try {
Method method = cls.getMethod(methodname, null);
Object retobj = method.invoke(this, null);
boolean ok = true;
if (retobj == null) {
ok = false;
}
else
if (fld.getType().getName()=="int") {
if (((Integer)retobj).intValue()<=0) ok = false;
}
if (ok) xml += "<" + fieldname + ">" + retobj + "</" + fieldname + ">";
}
catch(Exception ex) {
}
}
xml += "</"+ tagname + ">";
return xml;
}
}
例如,可以定义您的 JavaBean 为上述 Base 类的子类
public class MyBean extends Base {
private int id;
public int getId() { return id;
}
public void setId(int v) { id = v;}
public MyBean () {}
}
创建这个 Bean,赋值后就是输出 XML
MyBean mb = new MyBean();
mb.setId(100);
System.out.println(mb.toString());
结果是:
<MyBean><id>100</id></MyBean>
欢迎您试试更加复杂的 Java Bean。