java super.clone_浅析java中clone()方法

本文转载自:http://blog.csdn.net/mengxiangyue/article/details/6818611

Java中我们可能都遇到过这样的情况,在我们将一个对象做为参数传给一个函数的时候,我们希望在这个函数中所做的操做,并不会影响到这个对象本身。但是在java传递都是引用,所以往往我们在函数内部改变了对象的某一个值,在函数外面调用该对象的时候,相应的值也同样被改变了,例如下面的程序:

class Test

{

static void myMethod(Point pt1)

{

pt1.x = 23;

System.out.println("x="+pt1.x);

}

public static void main(String[] args)

{

Point pt = new Point(2,4);

System.out.println("x="+pt.x);

myMethod(pt);

System.out.println("x="+pt.x);

}

}

class Point{

int x,y;

Point (int x,int y)

{

this.x = x;

this.y = y;

}

}

输出的结果是

x=2

x=23

x=23

但是我们想要的结果是在我们调用了函数myMethod()方法后x的值不会改变,仍然是2。由于java中的传参是引用类型,所以会出现这样的结果,我们希望传递的是对象的一份拷贝,所以这里就用到了Object的clone()方法。

克隆的实现需要一下几步:

在派生类中覆盖基类的clone()方法,并声明为public。

在派生类的clone()方法中,调用super.clone()。

在派生类中实现Cloneable接口。Cloneable接口没有任何抽象的方法,这样的成为标识接口。实现这个接口,只是为了告诉编译器这个对象可以被克隆了。我们按照上面的步骤将上面的代码修改如下:

class Test

{

static void   myMethod(Point pt1)

{

pt1.x = 23;

System.out.println("x="+pt1.x);

}

public static void main(String[] args)

{

Point pt = new Point(2,4);

System.out.println("x="+pt.x);

Point pt2 = (Point)pt.clone();

myMethod(pt2);

System.out.println("x="+pt.x);

}

}

class Point implements Cloneable{

int x,y;

Point (int x,int y)

{

this.x = x;

this.y = y;

}

public Object clone()

{

Point p = null;

try

{

p = (Point)super.clone();

}

catch (Exception e)

{

e.printStackTrace();

}

return p;

}

}

输出的结果是:

x=2

x=23

x=2

首先我们在派生类中覆盖了Object类的Clone()方法,并声明为public的。然后我们调用了super.clone()方法,这里会抛出一个异常(对于这个异常大家可以自己查看java的帮助文档),所以必须用try……catch……语句捕获,然后返回此对象。这里需要说明一下,Clone()方法返回的是Object类型的,所以需要强制类型转换

对于javaclone()方法的浅析希望能给您带来帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
改进以下代码 currentpath = os.path.dirname(os.path.realpath(__file__)) time_date = '{}{}'.format(self.time_date,self.random_char(5)) contents = os.path.join(currentpath, time_date, self.ref.split('/')[-1]) ref = self.ref.split('/')[-1] private_token = self.gl.private_token path = "lib" if ref == "master": if os.path.exists(os.path.join(contents, self.name)): subprocess.call("rm -rf {} ".format(os.path.join(contents, self.name)), shell=True, cwd=contents) time.sleep(3) retcode = start.clone(int(self.project_id), ref, contents, private_token) if retcode == 0: start.clone_frontend(self.get_frontend()[0],self.get_frontend()[1], contents, private_token,self.get_frontend()[2] ) start.clone_abc(self.get_abc()[0], self.get_abc()[1], contents, private_token,"mc_abc") start.clone_model(start.get_clkrst()[0], start.get_clkrst()[1], contents, private_token,"clkrst") start.clone_model(start.get_ara()[0], start.get_ara()[1], contents, private_token,"ara") start.clone_model(start.get_wfl()[0], start.get_wfl()[1], contents, private_token,"wfl") subprocess.call("echo '*.t' >> {}".format(os.path.join(contents, self.name, ".gitignore")),shell=True) code = start.make_lib(os.path.join(contents, self.name)) rel, err = code.communicate() if "make: *** [main] Error 2" in err.decode('utf-8'): print("loading push error log") filename = os.path.join(contents, self.name, "error_make_log") subprocess.call("echo '' > {}".format(filename), shell=True, cwd=contents) start.error_make(filename, rel.decode('utf-8') ) start.error_make(filename, err.decode('utf-8') ) else: print("loading push libs") # start.push_lib(os.path.join(contents, self.name), path, ref)
06-01
以下是改进后的代码: ```python import os import time import subprocess class MyClass: def __init__(self, time_date, ref, project_id, private_token, name, frontend, abc, clkrst, ara, wfl): self.time_date = time_date self.ref = ref self.project_id = project_id self.private_token = private_token self.name = name self.frontend = frontend self.abc = abc self.clkrst = clkrst self.ara = ara self.wfl = wfl def random_char(self, y): # 生成随机字符串 pass def get_frontend(self): # 获取前端代码信息 pass def get_abc(self): # 获取abc代码信息 pass def get_clkrst(self): # 获取clkrst代码信息 pass def get_ara(self): # 获取ara代码信息 pass def get_wfl(self): # 获取wfl代码信息 pass def clone_repo(self): current_path = os.path.dirname(os.path.realpath(__file__)) time_date = '{}{}'.format(self.time_date, self.random_char(5)) contents = os.path.join(current_path, time_date, self.ref.split('/')[-1]) ref = self.ref.split('/')[-1] private_token = self.private_token path = "lib" if ref == "master": if os.path.exists(os.path.join(contents, self.name)): subprocess.call("rm -rf {} ".format(os.path.join(contents, self.name)), shell=True, cwd=contents) time.sleep(3) start = Start() # 实例化Start类 ret_code = start.clone(int(self.project_id), ref, contents, private_token) if ret_code == 0: start.clone_frontend(self.get_frontend()[0], self.get_frontend()[1], contents, private_token, self.get_frontend()[2]) start.clone_abc(self.get_abc()[0], self.get_abc()[1], contents, private_token, "mc_abc") start.clone_model(start.get_clkrst()[0], start.get_clkrst()[1], contents, private_token, "clkrst") start.clone_model(start.get_ara()[0], start.get_ara()[1], contents, private_token, "ara") start.clone_model(start.get_wfl()[0], start.get_wfl()[1], contents, private_token, "wfl") subprocess.call("echo '*.t' >> {}".format(os.path.join(contents, self.name, ".gitignore")), shell=True) code = start.make_lib(os.path.join(contents, self.name)) rel, err = code.communicate() if "make: *** [main] Error 2" in err.decode('utf-8'): print("loading push error log") filename = os.path.join(contents, self.name, "error_make_log") subprocess.call("echo '' > {}".format(filename), shell=True, cwd=contents) start.error_make(filename, rel.decode('utf-8')) start.error_make(filename, err.decode('utf-8')) else: print("loading push libs") # start.push_lib(os.path.join(contents, self.name), path, ref) ``` 这里对代码进行了一些改进: - 将获取当前路径和时间的代码合并到一起,使代码更加简洁。 - 将前端、abc、clkrst、ara和wfl的克隆操作集成到一个实例化Start类的方法,使代码更加模块化。 - 将错误日志的处理和推送操作分别封装到Start类的方法,使代码更加易于维护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值