克隆一例

王朝java/jsp·作者佚名  2006-01-09
宽屏版  字体: |||超大  

在一般的开发过程中,往往要遇到从数据库中取出数据组成值对象(通常叫做VO),然后放在列表集中,并传回调用端的情况。在还没有接触到clone的时候,程序往往要在while块中构造VO实例,但这样做并不推荐,甚至应该极力避免,因为会造成程序效率的低下。在使用clone技术以后,程序运行效率有所改善,以下是常用写法,希望对大家有所帮助。

支持clone的VO看起来像这样:

package com.XXX;

import java.util.*;

public class TempJob implements Cloneable { //声明其可被clone

private String Jbnr=null;

private String Jbdw=null;

public Object clone() {

try {

return super.clone(); //返回clone以后的对象

}

catch (CloneNotSupportedException e) {

System.out.println(e.toString());

}

public void setJbnr(String Jbnr){

this.Jbnr=Jbnr;

}

public String getJbnr(){

return Jbnr;

}

public void setJbdw(String Jbdw){

this.Jbdw=Jbdw;

}

public String getJbdw(){

return Jbdw;

}

}

对于调用VO的类,像这样:

package com.XXX;

import java.sql.*;

import java.util.*;

public class DoJob{

private Connection con;

private Statement stmt;

private ResultSet rs;

private ArrayList lis=new ArrayList();

public ArrayList query(String a){

String sql="";

sql="select a.*,b.name from temp_job a, user_basic b "

+"where a.userid = b.userid order by a.wcqk";

try{

stmt=con.createStatement();

rs=stmt.executeQuery(sql);

TempJob job=new TempJob(); //只要一个实例

while (rs.next()){

job.setJbnr(rs.getString(1));

job.setJbdw(rs.getString(2));

lis.add(job.clone()); //返回被clone对象

}

}

catch(SQLException e){

System.out.println(e.toString());

}

finally {

this.rs=null;

this.stmt=null;

con.close();

}

return lis;

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有