导航:首页 > 编程语言 > java克隆

java克隆

发布时间:2021-12-04 07:08:24

『壹』 java 对象克隆什么时候用

个人觉得,我们编程需要克隆的并不多,但是程序之间方法的调用、参数的传递是会使用克隆的。比如函数参数类型是自定义的类时,便是引用传递而不是值传递,这时候便克隆对象了一般用到的地方,是为了不破坏原对象的属性,在这个基础上创建新的克隆对象进行操作的安全性就能得到提高了

『贰』 java里的克隆重要吗

假如你是来新人的话,可以自不看,或者略微过下就行了
(可以以后等积累了一些经验再看,那样理解快)

如果有几年工作经验,想深造的话,还是仔细看看,里面有几个点是要注意的
不然真在工作遇到,不了解的话不比较麻烦

克隆其实功能还是很好的,只是很多人不懂细节,所以一般不用
但我现在在用,为什么有好功能不用

『叁』 Java中是如何实现克隆

java 实现clone对象方法抄的步骤如下:
(1)实现Cloneable接口
(2)重载Object类中的clone()方法,重载时需定义为public
(3)在重载方法中,调用super.clone()
例如:
class CloneClass implements Cloneable {
public int aInt;

public Object clone() {
CloneClass o = null;
try {
o = (CloneClass) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}

『肆』 java对象之间如何实现克隆(复制)

用clone()方法,不过在对象重载了Object的clone才能用。Object的clone方法是protected。

『伍』 java对象克隆

修改后的代码

classBook1implementsCloneable{
privateStringtitle;
privatedoubleprice;
publicBook1(Stringtitle,doubleprice){
this.title=title;
this.price=price;
}
publicvoidsetPrice(doubleprice){
this.price=price;
}
publicvoidsetTitle(Stringtitle){
this.title=title;
}
publicdoublegetPrice(){
returnprice;
}
publicStringgetTitle(){
returntitle;
}
protectedObjectclone(){
returnsuper.clone();
}
publicStringtoString(){
return"BOOK[title="+title+",price="+price+"]";
}
}
publicclassX{
publicstaticvoidmain(Stringargs[]){
Book1bookA=newBook1("JAVA从入门到精通",79.8);
Book1bookB;
try{ //加一个异常处理
bookB=(Book1)bookA.clone();
bookB.setPrice(100.8);
System.out.println(bookA);
System.out.println(bookB);
}catch(Exceptione){
}
}
}

『陆』 java如何实现对象的克隆

可以重载clone方法克隆对象

首先、该类要实现Cloneable的接口,不然执行clone方法内的时候会抛出CloneNotSupportedException异常

然后容、就在该类重载clone方法,自己加上克隆的逻辑,本人小白,手敲的代码

{

privateStringname;

publicBook(Stringname){
this.name=name;
}

@Override
publicBookclone(){
returnnewBook(this.name);
}
}

『柒』 java 如何拷贝

package czday0017;

import java.io.*;
import java.util.*;
/** IO 工具类 */
public class IO {
/**
* 获取目录的全部文件
* @param dir
* @return
*/
public static List<File> listFile(File dir){
return null;
}
/**
* 获取目录的全部文件, 指定扩展名的文件
* @param dir
* @return
*/
public static List<File> listFile(
File dir, String ext){
return null;
}
/**
* 递归获取目录的全部文件
* @param dir
* @return
*/
public static List<File> listAll(
File dir){
return null;
}
/**
* 递归获取目录的全部文件, 指定扩展名的文件
* @param dir
* @return
*/
public static List<File> listAll(
File dir, String ext){
return null;
}

/**
* 复制文件
*/
public static void cp(String from, String to)
throws IOException {
cp(new File(from), new File(to));
}
/**
* 复制文件
*/
public static void cp(File from, File to)
throws IOException {
cp(new FileInputStream(from),
new FileOutputStream(to));
}
/**
* 复制文件
*/
public static void cp(InputStream in,
OutputStream out)
throws IOException {
//1K byte 的缓冲区!
byte[] buf = new byte[1024];
int count;
while((count=in.read(buf))!=-1){
System.out.println(count);
out.write(buf, 0, count);
}
in.close();
out.close();
}
/**
* 从流中读取一行文本, 读取到一行的结束为止
* @param in
* @return 一行文本
*/
public static String readLine(
InputStream in, String charset)
throws IOException{
byte[] buf = {};
int b;
while(true){
b = in.read();
if(b=='\n' || b=='\r' || b==-1){//编码是否是回车换行
break;
}
buf=Arrays.Of(buf, buf.length+1);
buf[buf.length-1]=(byte)b;
}
if(buf.length==0 && b==-1)
return null;
return new String(buf,charset);
}

/**
* 读取文件的全部内容到一个byte数组
* 可以缓存一个"小"文件到堆内存中
*/
public static byte[] read(String filename)
throws IOException{
return read(new File(filename));
}
/**
* 读取文件的全部内容到一个byte数组
* 可以缓存一个"小"文件到堆内存中
*/
public static byte[] read(File file)
throws IOException{
//用RAF打开文件
RandomAccessFile raf =
new RandomAccessFile(file, "r");
//安装文件的长度开辟 缓冲区数组(byte数组)
byte[] buf = new byte[(int)raf.length()];
//读取文件的缓冲区
raf.read(buf);
//关闭文件(RAF)
raf.close();
//返回缓冲区数组引用.
return buf;
}
/**
* 读取文件的全部内容到一个byte数组
* 可以缓存一个"小"文件到堆内存中
* 如: 文件内容: ABC中 读取为: {41, 42, 43, d6, d0}
*/
public static byte[] read(InputStream in)
throws IOException{
byte[] ary = new byte[in.available()];
in.read(ary);
in.close();
return ary;
}
/**
* 连接byte 数组的全部内容为字符串,
* 以hex(十六进制)形式连接
* 如: 数组{0x41, 0x42, 0x43, 0xd6, 0xd0}
* 结果: "[41, 42, 43, d6, d0]"
*/
public static String join(byte[] ary){
if(ary==null || ary.length==0)
return "[]";
StringBuilder buf =
new StringBuilder();
buf.append("[").append(
leftPad(Integer.toHexString(ary[0]&0xff),'0',2));
for(int i=1; i<ary.length; i++){
String hex=Integer.toHexString(ary[i]&0xff);
buf.append(",").append(leftPad(hex,'0',2));
}
buf.append("]");
return buf.toString();
}

public static String toBinString(byte[] ary){
if(ary==null || ary.length==0)
return "[]";
StringBuilder buf =
new StringBuilder();
buf.append("[").append(
leftPad(Integer.toBinaryString(ary[0]&0xff),'0',8));
for(int i=1; i<ary.length; i++){
String hex=Integer.toBinaryString(ary[i]&0xff);
buf.append(",").append(leftPad(hex,'0',8));
}
buf.append("]");
return buf.toString();
}
/**
* 实现leftPad功能, 对字符串实现左填充
* @param str 被填充字符串: 5
* @param ch 填充字符: #
* @param length 填充以后的长度: 8
* @return "#######5"
*/
public static String leftPad(
String str, char ch, int length){
if(str.length() == length){
return str;
}
char[] chs = new char[length];
Arrays.fill(chs, ch);
System.array(str.toCharArray(), 0, chs,
length - str.length(), str.length());
return new String(chs);
}
/**
* 将text追加到文件 filename的尾部
* 使用系统默认文本编码
*/
public static void println (
String filename, String text)
throws IOException{
println(new File(filename),text);
}
public static void println(
File file, String text)throws IOException{
OutputStream out = new FileOutputStream(file,true);
println(out, text);
out.close();
}
/**
* 向流中输出一行字符串, 使用默认编码
* 不关闭流
* @param out 目标流
* @param text 文本
* @throws IOException
*/
public static void println(
OutputStream out, String text)throws IOException{
out.write(text.getBytes());
out.write('\n');
}
/**
* 向流中输出一行字符串, 使用指定的编码
* 不关闭流
* @param out 目标流
* @param text 文本
* @param charset 指定的编码
* @throws IOException
*/
public static void println(
OutputStream out, String text, String charset)throws IOException{
out.write(text.getBytes(charset));
out.write('\n');
}
/**
* 文件切分
* @param file
* @param size
* @throws IOException
*/
public static void spilt(String file,int size) throws IOException{
if(size<=0){
throw new IllegalArgumentException("干吗啊!输入有误阿!");
}
int idx = 0;//文件序号
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(new FileOutputStream(file+"."+idx++));
int b;
int count = 0;
while((b = in.read())!=-1){
out.write(b);
count++;
if(count%(size*1024)==0 ){
out.close();
out = new BufferedOutputStream(new FileOutputStream(file+"."+idx++));
}
}
in.close();
out.close();
}
/**
* 将文件进行连接
* @param filename是一个文件名;如:file.dat.0
*/
public static void join(String file)throws IOException{
String filename = file.substring(0, file.lastIndexOf("."));
String num = file.substring(file.lastIndexOf(".")+1);
int idx = Integer.parseInt(num);
OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
File f = new File(filename+"."+idx++);
while(f.exists()){
InputStream in = new BufferedInputStream(new FileInputStream(f));
cp(in,out);
in.close();
f = new File(filename+"."+idx++);
}
out.close();
}
/**
* 序列化对象
*/
public static byte[] Serialize(Serializable obj)throws IOException{
return null;
}

public static Object unSerializable(byte[] data)throws IOException{
return null;
}

public static Object clone(Serializable obj)throws IOException{
return unSerializable(Serialize(obj)) ;
}
}

//使用cp工具!

『捌』 java中的克隆技术具体有什么应用

Clone基本知识储备
在Java里提到clone技术,就不能不提java.lang.Cloneable接口和含有clone方法的Object类。所有具有clone功能的类都有一个特性,那就是它直接或间接地实现了Cloneable接口。否则,我们在尝试调用clone()方法时,将会触发CloneNotSupportedException异常。 下面我们通过对Object类的部分源码的分析,来发现和理解这一特性。
l clone的实现

1.实现Cloneable接口

通过上一篇的介绍,我们知道,一个类若要具备clone功能,就必须实现Cloneable接口。做到这一步,clone功能已经基本实现了。Clone功能对我们来说,最主要的还是要能够使用它。那么我们如何才能使用clone功能呢?答案是覆盖Object#clone()方法。

2. 覆盖Object#clone()方法

为什么需要覆盖Object#clone()方法?这里得再次从jdk源码说起。JDK中Object# clone()方法的原型是:

protected native Object clone() throws CloneNotSupportedException;

是否注意到,这里clone()方法修饰符是protected,而不是public。这种访问的不可见性使得我们对Object#clone()方法不可见。相信读者已明白为什么要覆盖Object#clone()方法。而且,覆盖的方法的修饰符必须是public,如果还保留为protected,覆盖将变得没有实际意义。下面举一个具有clone功能的简单的例子:

/*

* 具有clone功能的类的例子

*/

public class CloneableObjExample implements Cloneable {

//……部分代码已省略……

private String name = null;

private int score = 0;

/**

* NOTE: 将protected 修饰符 更改为 public

* @see java.lang.Object#clone()

*/

public/*protected*/ Object clone() throws CloneNotSupportedException {

// call父类的clone方法

Object result = super.clone();

//TODO: 定制clone数据

return result;

}

}

3.定制clone

至此,clone已经真相大白。Clone的对象我们可以对其进行定制。还就上面的例子来说。下面的方法对功能做了一定的增强:

public/*protected*/ Object clone() throws CloneNotSupportedException {

// call父类的clone方法

CloneableObjExample result = (CloneableObjExample)super.clone();

//TODO: 定制clone数据

//虽然”clone”了,但还可以做点调整

result.name = “New Name”;

result.score = 90;

return result;

}

本篇介绍了如何实现clone。接下来的篇幅将就纵深clone等clone的高级特性进行分析。

本章将进入clone的高级特性,着重讲述纵深clone技术。

Clone通常有两种类型即浅clone和深clone。首先,分析一下两种的不同。浅clone和深clone都是clone,它们本质区别是对象内部的成员属性(非原生类型属性,如int等)在clone时是否处理为引用。如果仍然保留为引用,则称为浅clone,反之称为深clone。其实这两个概念也是相对的概念。在处理上它们有点区别,浅clone方式得到clone对象即可,深clone方式在得到clone对象后,还需要对引用的成员属性进行“clone”处理。从这个层次上说,深clone并没有什么特别地困难,简单讲就是创建好对象,再设置一些成员属性。关于深clone,网上的文章已经有太多,有点目不暇接的感觉,本文不再赘述,这也不是本文的重点。

本文的重点是要阐述纵深clone,亦即“N深clone”。深到什么程度为止?本文描述的目标是一直深到你想要的程度,包括深到不能再深的程度。

『玖』 java 对象 克隆

这是里面的一段(非完整的例子):
public class Snake implements Cloneable {

...........................

public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {}
return o;

}
书上一段给你看看,希望有帮助把。。
当制作实例变量的一个引用时,原始实例变量和副本实力变量在内存中引用的均是同一个存储空间,这就意味着但对其中一个实例变量操作时就会影响到这个对象的副本。例如下面的程序代码。在执行时将会看到所画的两条线重合在一起,都是改变后的LineFigure1。
LineFigure lineFigure1 = new LineFigure();
LineFigure lineFigure2 = lineFigure1;
lineFigure1.draw(g);
…code for changing lineFigure1
lineFigure2.draw(g);
如果想让LineFigure2成为一个新的对象,就要用到Clone( )方法。Clone的后对象和原对象的存储空间不同,改变其中一个并不会对另一个产生任何影响。例如下面代码所示:
…………….
LineFigure2 = lineFigure1.clone();
…………….
如果LineFigure2中没有对其他对象的引用,事情就到此结束了,但LineFigure类中的实例变量StartPoint和EndPoint都是一个对象,即使简单地实现了对LineFigure1地Clone,可LineFigure1和LineFigure2的StartPoint和EndPoint实例变量引用的是同一个变量,要想完全的实现将LineFigure2和LineFigure1分离开,就要实现Cloneable接口,并重写Clone方法。Cloneable接口是Java提供的少数几个标签化接口之一。平常所说的标签化接口就是不提供任何方法的接口。在图形白板程序中,也用到了Cloneable接口,例如LineFigure类中的代码:
public class LineFigure extends Figure implements Cloneable{
public Object clone(){
LineFigure lineFigure = new LineFigure();
lineFigure.startPoint = (Point)startPoint.clone();
lineFigure.endPoint = (Point)endPoint.clone();
lineFigure.firstDraw = firstDraw;
return lineFigure;
}
………………..
}
这样一来,LineFigure1和LineFigure2所引用的对象就没有任何的重合。对其中任何一个进行修改而不影响另一个的应用。

『拾』 如何克隆Java对象

Java中的对象涉及使用引用类型,没有直接的方法可将一个对象的内容复制到一个新对象中。将一个引用分配给另一个引用只会给相同对象建立另一个引用。因此,Java对所有引用类型使用一个特殊的clone()方法,为对象复制自身提供一个标准的机制。以下是你需要了解和克隆Java对象有关的细节。为何建立一个本地拷贝?给一个对象建立本地拷贝的原因很可能是由于你计划修改该对象,并且你不想修改方法调用者的对象。如果你确定你需要一个本地拷贝,你可以使用Object类的clone()方法来执行这项操作。clone()方法被定义为受保护方法,但你必须在你希望克隆的所有子类中重新公开定义它。例如,标准库类ArrayList忽略clone(),但你可以这样为ArrayList调用clone()方法:import java.util.*;class MyInt {private int i;public MyInt(int ii) { i = ii; }public void increment() { i++; }public String toString() {return Integer.toString(i);}}public class Test {public static void main(String[] args) {ArrayList al = new ArrayList();for(int i = 0; i < 10; i++ )al.add(new MyInt(i));ArrayList al1 = (ArrayList)al.clone();// Increment all al1’s elements:for(Iterator e = al1.iterator(); e.hasNext(); ) ((MyInt)e.next()).increment();}}clone()方法生成一个Object,它必须重新转变为适当的类型。这个例子说明ArrayList的clone()方法如何不能自动克隆ArrayList包含的每一个对象?原有ArrayList和克隆后的ArrayList是相同对象的别名。这种情况通常叫做浅拷贝,因为它仅仅复制一个对象的“表面”部分。实际的对象由这个“表面”,引用指向的所有对象,以及那些对象指向的所有对象等构成。这往往被称作“对象网络”。下一页>>

阅读全文

与java克隆相关的资料

热点内容
授权的苹果手机u盘 浏览:983
cad如何跨文件复制保持尺寸 浏览:240
苹果手机显示在桌面的按键圆圈 浏览:229
班级怎么创建网站 浏览:26
win10系统重装只剩c盘 浏览:972
句馆app怎么用 浏览:98
极速下载管家的文件路径 浏览:535
网站产品是什么意思 浏览:183
苹果电脑怎么压缩视频文件怎么打开 浏览:435
app的发展趋势国家政策报告 浏览:895
字符串反转java 浏览:321
如何制作安装系统镜像文件 浏览:399
win10文件夹左上角有红点 浏览:487
你为什么学plc编程 浏览:828
网络连接没了 浏览:991
代码打印pdf 浏览:563
扣扣红包网络连接失败 浏览:301
win10商城下载文件在哪 浏览:975
系统制作镜像文件 浏览:249
苹果手机指纹贴有危险 浏览:329

友情链接