用另一个和所有引用替换 Java 对象实例 [英] Replace Java object instance with another and all references

查看:57
本文介绍了用另一个和所有引用替换 Java 对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用另一个对象替换 java 中的一个对象,该对象将所有对第一个对象的引用更新为指向第二个对象?在 C# 中,这里回答了这个问题:用 C# 中的另一个替换对象实例 但我想知道我是否可以在 Java 中做到这一点.谢谢!

is there a way to replace an object in java with another one that updates all references to the first one to instead point to the second one? In C# this question was answered here: Replace object instance with another in C# but I was wondering if I could do this in Java. Thanks!

1. 我想用一个子类型的对象替换第一个对象.2. 我无法编辑第一个对象的实现,这就是我用子类型替换它的原因.我可以编辑子类型.

1. I want to replace the first object with a an object of a subtype. 2. I can't edit the implementation of the first object, that's why I'm replacing it with a subtype. I can edit the subtype.

推荐答案

即使可以,也不要这样做.相反,使用另一个类来包含或包装要替换的对象.容器必须通过调用原始中的方法从原始中实现您需要的所有方法,但是您可以随时轻松替换包装类.包装器、原始类和替换它的类都应该实现相同的接口.这个解决方案有点麻烦,但随着时间的推移它会持续下去.

Don't don't this, even if you can. Instead, use another class to contain or wrap the object you want to replace. The container has to implement all the methods you need from the original by calling the methods in the original, but you can replace the wrapped class easily at any time. The wrapper, the original class, and the one you replace it with should all implement the same interface. This solution's a bit of work, but it will hold up over time.

我怀疑您真正想要的是一个具有许多可升级组成部分的类,但这对初学者来说是可行的,并且可以让您以正确的方式思考.

I suspect what you really want is a class that has a number of upgradable component parts, but this will do for starters, and get you thinking the right way.

这篇关于用另一个和所有引用替换 Java 对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆