如何获得 c++ Java 中的常量指针等效吗?
当我将不可变类型对象(String、Integer、..)作为final传递给方法时,我可以获得C++常量指针的字符。 但是如何在可变对象中强制执行这种行为呢?
public void someMethod(someType someObject){
/*
* code that modifies the someObject's state
*
*/
}
我想要的只是阻止 someMethod 修改 someObject 的状态而不对 someType 进行任何更改。 这可能吗?
When I pass an immutable type object(String, Integer,.. ) as final to a method I can achieve the characters of a C++ constant pointer. But how can I enforce such behavior in objects which are mutable?
public void someMethod(someType someObject){
/*
* code that modifies the someObject's state
*
*/
}
All I want is to prevent someMethod from modifying the state of someObject without making any change in someType. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在一般情况下,不,这是不可能的。 在非常有限的情况下,您可以将 someType 包装在提供相同接口的类中(有关示例,请参阅 Collections.unmodifyingList() )。
但是,没有相当于“传递 const 指针,编译器将只允许您在其上调用 const 函数”。
In the general case, no, it's not possible. In a very limited case, you can wrap someType in a class that provides the same interface (see Collections.unmodifiableList() for an example).
However, there's no equivalent to "pass a const pointer and the compiler will only allow you to call const functions on it".
不,您无法阻止通过其 setXXX() (或类似)方法修改对象。 不过,您可以提交它的克隆版或副本。
No, you can not prevent the object being modified via its setXXX() (or similar) methods. You could hand in a clone or a copy of it, though.
不,我认为这是不可能的。 正常的方法是为 SomeType 创建一个适配器,其中所有更改状态的方法都会抛出 UnsupportedOperationException。 例如 java.util.Collections.unmodifying*-functions 使用它。
有几种方法可以实现这一点:
这当然只会为您提供运行时检查,而不是编译时检查。 如果你想要编译时,你可以让 SomeType 成为一个接口(或超类),没有写入方法,只能读取。
No, I don't think this is possible. The normal approach is to create an adapter for SomeType where all the methods changing state throws UnsupportedOperationException. This is used by for instance java.util.Collections.unmodifiable*-functions.
There are several approaches to this:
This will of course only give you run-time checking, not compiletime. If you want compile-time, you can let SomeType be an interface (or a superclass) with no write-methods, only read.
不,这是不可能的。 您必须传递对象的副本,或者仅依赖于知道哪些操作会对对象进行状态更改并避免调用它们 - 编译器不会帮助您。
No, it's not possible. You have to either pass in a copy of the object, or just rely on knowing what actions make state changes to the object and avoid calling them - the compiler won't help you.