Is it possible to make an object “Read Only” to a method

后端 未结 11 1952
攒了一身酷
攒了一身酷 2020-12-29 06:33

If an object reference is passed to a method, is it possible to make the object \"Read Only\" to the method?

11条回答
  •  佛祖请我去吃肉
    2020-12-29 06:42

    Expanding on ewernli's answer...

    If you own the classes, you can use read-only interfaces so that methods using a read-only reference of the object can only get read-only copies of the children; while the main class returns the writable versions.

    example

    public interface ReadOnlyA {
        public ReadOnlyA getA();
    }
    
    public class A implements ReadOnlyA {
        @Override
        public A getA() {
            return this;
        }
    
        public static void main(String[] cheese) {
            ReadOnlyA test= new A();
            ReadOnlyA b1 = test.getA();
            A b2 = test.getA(); //compile error
        }
    }
    

    If you don't own the classes, you could extend the class, overriding the setters to throw an error or no-op, and use separate setters. This would effectively make the base class reference the read-only one, however this can easily lead to confusion and hard to understand bugs, so make sure it is well documented.

提交回复
热议问题