您的位置:首页 > 编程语言 > Java开发

Java 反射机制初探(一)--仿hibernate持久化实现

2009-07-29 14:23 731 查看
Java 反射机制使用

反射机制 基础:
用例子作为说明,相信很好理解。

package com.ghrt.programmer;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
* author : zhangyinlong

* date :2009/06/25
* content:反射机制:所谓的反射机制就是java语言在运行时拥有一项自观的能力。
* 通过这种能力可以彻底的了解自身的情况为下一步的动作做准备。

* 该类通过代码说明 java 反射的用法
*/
public class ReflectionTest {

/*
*根据类名的字符串打印该类的所有方法
* @parameter className : 类的全名,例如 "java.utill.List"
*/
public void printMethodByClassname(String className)
{
try {

Class c = Class.forName(className);

//打印出所有方法
System.out.println("打印出所有方法");
Method m[] = c.getDeclaredMethods();
for(int i=0;i<m.length;i++)
{
System.out.println(m[i].toString());
}

//打印出类声明的所有字段
System.out.println("打印出类声明的所有字段");
Field f[] = c.getDeclaredFields();
for(int i=0;i<f.length;i++)
{
System.out.println(f[i]);
}

//打印出该类声明的所有构造函数
System.out.println("打印出该类声明的所有构造函数");
Constructor ct[] = c.getDeclaredConstructors();
for(int i=0;i<ct.length;i++)
{
System.out.println(ct[i]);
}

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
//测试方法
public void test(String str)
{
System.out.println(str);
}
//既然可以通过反射获得类的所有属性和方法,那 通过反射调用测试类的方法 也是很容易的
public void useMethodByReflection()
{
try {
//通过反射获得 “com.ghrt.programmer.RelectionTest” 这个类
Class c = Class.forName("com.ghrt.programmer.ReflectionTest");
//实例化该类的对象
Object obj = c.newInstance();

//根据方法名和参数类型获得该对象的方法
Class[] types = new Class[1];
types[0] = Class.forName("java.lang.String");
Method m = c.getDeclaredMethod("test",types);

//执行方法
m.invoke(obj, new Object[]{"aaa"});

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

ReflectionTest rt = new ReflectionTest();
rt.useMethodByReflection();
//rt.printMethodByClassname("java.util.ArrayList");

}

}

java 反射的应用
反射的应用不能不提到 hibernate 的框架,hibernate 可以使我们轻松的进行数据库的操作,
传递一个查询语句(类似 "select id,name from userInfo"),hibernate 会自动的将符合条件的
对象封装的list里面,供我们调用,大大简化了我们的代码量。下面就以一段代码模仿hibernate
的实现。

代码片段一(一般的查询方法):
/**
* 通用的查询方法
* 通过SQL语句,与传递进来的object
* 将查询出来的sql结果,通过反射机制封装至object
* 注: ojbect必须为POJO,或BEAN的类
* @param sql 查询SQL
* @param objName 需要返回的列表内包含对象的类型
* @return 封装好的对象
*/
public List getResult(String sql,String objName,int db_flag) throws Exception
{

PreparedStatement stmt = null;
ResultSet rs = null;
RecordReflection rr = null;

//获得数据库的连接
dbConnection = new DbConn1().getDBConnection();
if(dbConnection != null) System.out.println("GetConn successful");

List result = null;
try {

stmt = dbConnection.prepareStatement(sql);
rs = stmt.executeQuery();
if(rs != null){
System.out.println("GetRS successful");
}

//具体内容见代码片段2
rr = new RecordReflection();
//通过传递 结果集 和 “对象的全名” 返回 对象列表,和 普通查询 这一步不同
result = rr.Relection(rs, objName);

} catch (SQLException ex) {
log.error("getResult is error:" + ex.getMessage());
ex.printStackTrace();
} finally {
this.closeResultSet(rs);
this.closeStatement(stmt);
this.closeConnection();
}

return result; //返回范类型集合,该集合中存储着符合条件的行与列
}

代码片段二(RecordReflection 类):
package com.ghrt.frame;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

public class RecordReflection {

private Logger log = Logger.getLogger(RecordReflection.class);

/**
* 通过传递进来的ResultSet与对象名称,序列化为对象,塞入list
* @param rs 结果集
* @param objName 对象
* @return list list里存储传递的objName的对象
*/
public List Relection(ResultSet rs,String objName){
List list = null;
try{
List resultList = this.ProcessResultSet(rs);
list = this.ProcessObject(resultList, objName);

}catch(Exception e){
log.error("Relection is error:" + e.getMessage());
}
return list;
}

public List ProcessResultSet(ResultSet rs) throws PlatformException{

List listResult =new ArrayList();
int cols = 0;
String colName="";
String colType="";
String colValue="";
try{
if(rs == null) //判断是否结果集为空,如果为空,直接返回
return null;

LabelValue lv = null; //见代码片段3

List list = new ArrayList<LabelValue>();
ResultSetMetaData rsetMd = null;
rsetMd = rs.getMetaData();
cols = rsetMd.getColumnCount();
while(rs.next()){

list = new ArrayList<LabelValue>();
for (int i=0;i<cols;i++){
colName = rsetMd.getColumnName(i+1);
colType = rsetMd.getColumnTypeName(i+1);
colValue = rs.getString(i+1);
lv = new LabelValue();
lv.setName(colName);
lv.setType(colType);
lv.setValue(colValue);

list.add(lv);
}

listResult.add(list);
}

}catch(Exception e){
log.error(" // Relection process ResultSet is error // " + e.getMessage());
throw new PlatformException("class RecordReflection ProcessResultSet is error: " + e.getMessage());
}
return listResult;
}

public List ProcessObject(List list,String objName) throws PlatformException{

List resultList = null;
try{
resultList = new ArrayList();
log.debug(" // list.size:" + list.size());
Iterator it = list.iterator();

while(it.hasNext()){//获取每条记录
List lvList = (List)it.next();
log.debug(" // lvList.size:" + lvList.size());

System.out.println("lvList:"+lvList.size());
Iterator lvIt = lvList.iterator();

Class clazz = Class.forName(objName);
Object obj = clazz.newInstance();

while(lvIt.hasNext()){//获取记录里的每个字段
LabelValue lv = (LabelValue)lvIt.next();
//获取生成的object对象

Field[] fields = clazz.getDeclaredFields();
log.debug("// fileds.length // "+fields.length);
// for(Field field:fields){
for(int i = 0;i<fields.length;i++){
Field field = fields[i];
System.out.println(fields[i]);
log.debug("getname:"+field.getName()+" // lv.getName // "+lv.getName());
String fieldName = field.getName();

if(fieldName.equalsIgnoreCase(lv.getName())){
log.debug(" // fieldName//" + fieldName +" // fieldType //" + field.getType().getName());
log.debug(" // lv.getName // " + lv.getName() + " // lv.value // " + lv.getValue());
Method method = clazz.getDeclaredMethod("set"+
fieldName.substring(0,1).toUpperCase()+fieldName.substring(1)
,new Class[]{field.getType()});
if(field.getType().equals(String.class)){ //处理当为String类型情况
method.invoke(obj, new Object[]{this.toString(lv.getValue())});
}else if(field.getType().equals(Integer.class)){//处理当为Integer类型情况
method.invoke(obj, new Object[]{this.toInteger(lv.getValue())});
}else if(field.getType().equals(Float.class)){//处理当为Float类型情况
method.invoke(obj, new Object[]{this.toFloat(lv.getValue())});
}else if(field.getType().equals(Double.class)){//处理当为Double类型情况
method.invoke(obj, new Object[]{this.toDouble(lv.getValue())});
}else if(field.getType().equals(BigDecimal.class)){//处理当为BigDecimal类型情况
method.invoke(obj, new Object[]{this.toBigDecimal(lv.getValue())});
}else if(field.getType().equals(Long.class)){//处理当为Long类型情况
method.invoke(obj, new Object[]{this.toLong(lv.getValue())});
}else if(field.getType().equals(Timestamp.class)){//处理当为Timestamp类型情况
method.invoke(obj, new Object[]{this.toTimestamp(lv.getValue())});
}else if(field.getType().equals(int.class)){//处理当为int类型情况
method.invoke(obj, new Object[]{this.toInteger(lv.getValue())});
}else if(field.getType().equals(float.class)){//处理当为float类型情况
method.invoke(obj, new Object[]{this.toFloat(lv.getValue())});
}else if(field.getType().equals(double.class)){//处理当为double类型情况
method.invoke(obj, new Object[]{this.toDouble(lv.getValue())});
}else if(field.getType().equals(Date.class)){//处理当为Date类型情况
method.invoke(obj, new Object[]{this.toTimestamp(lv.getValue())});
}else if(field.getType().equals(short.class)){//处理当为Short类型情况
log.debug(" // parse short // ");
method.invoke(obj, new Object[]{this.toShort(lv.getValue())});
}

}

}
}

resultList.add(obj);
}
}catch(Exception ex){
log.error(" // process object is error // " + ex.getMessage());
throw new PlatformException("class RecordReflection ProcessObject is error: " + ex.getMessage());
}
return resultList;
}

/**
* 对Date类型转换
* @param args
* @return
*/
public Date toDate(String args){
Date result = null;
if(null == args || "".equals(args))
result = null;
else
try{
// result = BigDecimal.parseBigDecimal(args);
result = new Date(args);
}catch(Exception e){
result = null;
log.error(" // RecordReflection parse Date is error // " + e.getMessage());
}

return result;
}
/**
* 对Timestamp类型转换
* @param args
* @return
*/
public Timestamp toTimestamp(String args){
Timestamp result = null;
if(null == args || "".equals(args))
result = null;
else
try{
// result = BigDecimal.parseBigDecimal(args);
result = Timestamp.valueOf(args);
}catch(Exception e){
result = null;
log.error(" // RecordReflection parse Timestamp is error // " + e.getMessage());
}

return result;
}
/**
* 对BigDecimal类型转换
* @param args
* @return
*/
public BigDecimal toBigDecimal(String args){
BigDecimal result = null;
if(null == args || "".equals(args))
result = new BigDecimal(0);
else
try{
// result = BigDecimal.parseBigDecimal(args);
result = new BigDecimal(args);
}catch(Exception e){
result = new BigDecimal(0);
log.error(" // RecordReflection parse BigDecimal is error // " + e.getMessage());
}

return result;
}
/**
* 对Long类型转换
* @param args
* @return
*/
public Long toLong(String args){
Long result = null;
if(null == args || "".equals(args))
result = new Long(0);
else
try{
result = Long.parseLong(args);
}catch(Exception e){
result = new Long(0);
log.error(" // RecordReflection parse Long is error // " + e.getMessage());
}

return result;
}
/**
* 对Double类型转换
* @param args
* @return
*/
public Double toDouble(String args){
Double result = null;
if(null == args || "".equals(args))
result = new Double(0);
else
try{
result = Double.parseDouble(args);
}catch(Exception e){
result = new Double(0);
log.error(" // RecordReflection parse Double is error // " + e.getMessage());
}

return result;
}
/**
* 对Float类型转换
* @param args
* @return
*/
public Float toFloat(String args){
Float result = null;
if(null == args || "".equals(args))
result = new Float(0);
else
try{
result = Float.parseFloat(args);
}catch(Exception e){
result = new Float(0);
log.error(" // RecordReflection parse Float is error // " + e.getMessage());
}

return result;
}
/**
* 对Integer类型转换
* @param args
* @return
*/
public Integer toInteger(String args){
Integer result = null;
if(null == args || "".equals(args))
result = 0;
else{
try{
result = Integer.parseInt(args);
}catch(Exception e){
result = 0;
log.error(" // RecordReflection parse Integer is error // " + e.getMessage());
}
}
return result;
}

/**
* 对Short类型转换
* @param args
* @return
*/
public Short toShort(String args){
Short result = null;
if(null == args || "".equals(args))
result = 0;
else{
try{
result = Short.parseShort(args);
}catch(Exception e){
result = 0;
log.error(" // RecordReflection parse Short is error // " + e.getMessage());
}
}
return result;
}

/**
* 重写了对String类型的转换
* @param args
* @return
*/
public String toString(String args){
String result = null;
if (null == args || "".equals(args))
result = "";
else
result = args.toString();
return result;
}

}

代码片段3(LabelValue 类):
package com.ghrt.frame;

import java.io.Serializable;

public class LabelValue implements Serializable{

private String name;
private String value;
private String type;
private int id;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: