本文是“
使用反射简化繁琐的对对象成员设值取值的过程”的续文。
在前文的例子中,类MemberInfo的成员变量都是String类型,如果说其中有其它类型int,boolean等,如果变成下面的类:
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
public class Member
{
private String name;
private String title;
private int age;
private boolean isMale;
}
这样以前的给字段设置值的方法就不好用了,如之奈何?
其实只要肯想,办法是有的,反射的getField不好用了,我们还有getMethod,胡屠户死了,咱们也不吃带毛的猪。通过反射的getMethod方法,咱们可以得到类中定义的函数,再对类的getter、setter函数动动手脚就能达到我们的目的。
请看代码,特别是带注释的动了手脚的函数部分。
新定义的Member类:
package com.sitinspring;
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
public class Member
{
private String name;
private String title;
private int age;
private boolean isMale;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public Member()
{
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public Member(String name,String title,int age,boolean isMale)
{
this.name=name;
this.title=title;
this.age=age;
this.isMale=isMale;
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 额外增加的从整数类型年龄得到为字符状态年龄的函数
* @return
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public String getAge()
{
return String.valueOf(age);
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 额外增加的将字符状态年龄转化为整数类型年龄的函数
* @param age
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void setAge(String age)
{
this.age = Integer.valueOf(age);
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 额外增加的取得字符类型性别的函数
* @return
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public String getIsMale()
{
return isMale?"男":"女";
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 额外增加的将字符类型性别转化为布尔类型性别的函数
* @param strMale
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void setIsMale(String strMale)
{
this.isMale = strMale.equals("男");
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 改写的函数,将生成的getAge变成了getIntAge
* @return
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public int getIntAge()
{
return age;
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public String toString()
{
return "Name="+name+" Title="+title+" Age="+age+" 性别="+getIsMale();
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public String getName()
{
return name;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void setName(String name)
{
this.name = name;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public String getTitle()
{
return title;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void setTitle(String title)
{
this.title = title;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void setAge(int age)
{
this.age = age;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public boolean isMale()
{
return isMale;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void setMale(boolean isMale)
{
this.isMale = isMale;
}
}
上面四个函数就是为了方便反射而写的,再看MemberPersistence的代码:
package com.sitinspring;
![](/Images/OutliningIndicators/None.gif)
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
![](/Images/OutliningIndicators/None.gif)
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
/** *//**
* 用于将Member类实例存到XML文件及从XML文件中取出
*
* @author: sitinspring(junglesong@gmail.com)
* @date: 2008-1-3
*/
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
public class MemberPersistence
{
// XML 文件名
private final String xmlFile;
![](/Images/OutliningIndicators/InBlock.gif)
// XML 文档对象
private Document document;
![](/Images/OutliningIndicators/InBlock.gif)
// XML 文档根节点
private Element root;
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 构造函数,其中实例化文档对象和根节点
*
* @param xmlFile
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public MemberPersistence(String xmlFile)
{
this.xmlFile = xmlFile;
![](/Images/OutliningIndicators/InBlock.gif)
File file = new File(xmlFile);
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
// 判断文件的存在以增强程序的健壮性
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if (file.exists())
{
// 文件存在,直接从文件读取文档对象
SAXReader reader = new SAXReader();
document = reader.read(file);
root = document.getRootElement();
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} else
{
// 文件不存在,创建文档对象
document = DocumentHelper.createDocument();
root = document.addElement("companies");// 创建根节点
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} catch (Exception ex)
{
ex.printStackTrace();
}
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 从XML文件中提取所有Member节点的信息,作为链表返回
*
* @return
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public List<Member> loadFromXml()
{
List<Member> retval = new ArrayList<Member>();
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
List nodes = root.elements("member");
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for (Iterator it = nodes.iterator(); it.hasNext();)
{
Element memberElm = (Element) it.next();
![](/Images/OutliningIndicators/InBlock.gif)
Member member = new Member();
![](/Images/OutliningIndicators/InBlock.gif)
// 取得MemberInfo类的所有定义的成员变量,注意DeclaredFields不包括继承下来的成员变量
Field[] fields = member.getClass().getDeclaredFields();
![](/Images/OutliningIndicators/InBlock.gif)
// 设置每个成员变量的值
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for (Field field : fields)
{
String fieldText = memberElm.elementText(field.getName());
![](/Images/OutliningIndicators/InBlock.gif)
// 通过反射取得setter函数(通过getSetMethodName函数得出,参数为成员名),其参数为String
Method method = member.getClass().getMethod(
getSetMethodName(field.getName()),
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
new Class[]
{ String.class });
![](/Images/OutliningIndicators/InBlock.gif)
// 通过反射调用setter函数给成员变量赋值
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
method.invoke(member, new Object[]
{ fieldText });
}
![](/Images/OutliningIndicators/InBlock.gif)
retval.add(member);
}
![](/Images/OutliningIndicators/InBlock.gif)
return retval;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} catch (Exception ex)
{
ex.printStackTrace();
}
![](/Images/OutliningIndicators/InBlock.gif)
return null;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 将一个Member对象写到XML文件中
*
* @param member
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void writeToXml(Member member)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
// 在根节点下增加一个member节点
Element memberElm = root.addElement("member");
![](/Images/OutliningIndicators/InBlock.gif)
// 取得MemberInfo类的所有定义的成员变量,注意DeclaredFields不包括继承下来的成员变量
Field[] fields = member.getClass().getDeclaredFields();
![](/Images/OutliningIndicators/InBlock.gif)
// 取得每个成员变量的值
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for (Field field : fields)
{
// 在member节点下添加属性节点
Element fieldElm = memberElm.addElement(field.getName());
![](/Images/OutliningIndicators/InBlock.gif)
// 通过反射取得getter函数(通过getGetMethodName函数得出,参数为成员名),其参数无
Method method = member.getClass().getMethod(
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
getGetMethodName(field.getName()), new Class[]
{});
![](/Images/OutliningIndicators/InBlock.gif)
// 通过反射调用getter函数给取得成员变量的值
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
Object result = method.invoke(member, new Object[]
{});
![](/Images/OutliningIndicators/InBlock.gif)
// 将此值赋给节点文字
fieldElm.setText((String) result);
}
![](/Images/OutliningIndicators/InBlock.gif)
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK"); // 指定XML编码
XMLWriter writer = new XMLWriter(new FileWriter(xmlFile), format);
![](/Images/OutliningIndicators/InBlock.gif)
writer.write(document);
writer.close();
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} catch (Exception ex)
{
ex.printStackTrace();
}
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 取得“getter”函數的函數名
*
* @param field
* @return
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
private static String getGetMethodName(String field)
{
return "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* 取得“setter”函數的函數名
*
* @param field
* @return
*/
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
private static String getSetMethodName(String field)
{
return "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
}
}
![](/Images/OutliningIndicators/None.gif)
最后的调用处还是和上篇差不多:
package com.sitinspring;
![](/Images/OutliningIndicators/None.gif)
import java.util.List;
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
public class Main
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public static void main(String[] args)
{
MemberPersistence persistence=new MemberPersistence("member.xml");
// 1.写入过程
Member andy=new Member("Andy","SSE",25,true);
Member bill=new Member("Bill","PM",26,false);
persistence.writeToXml(andy);
persistence.writeToXml(bill);
// 2.读出过程
List<Member> members=persistence.loadFromXml();
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for(Member member:members)
{
System.out.println(member);
}
}
}
生成的文件:
<?xml version="1.0" encoding="GBK"?>
![](/Images/OutliningIndicators/None.gif)
<companies>
<member>
<name>Andy</name>
<title>SSE</title>
<age>25</age>
<isMale>男</isMale>
</member>
<member>
<name>Bill</name>
<title>PM</title>
<age>26</age>
<isMale>女</isMale>
</member>
</companies>
![](/Images/OutliningIndicators/None.gif)
代码下载(请自行加入dom4j包):
http://www.blogjava.net/Files/sitinspring/MemberMethodSetgetValueSample20080105151118.rar