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

后端 未结 11 1955
攒了一身酷
攒了一身酷 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:39

    You could achieve a similar thing in most cases by cloning the Object as the first statement of the method, such as this...

    public void readOnlyMethod(Object test){
        test = test.clone();
        // other code here
    }
    

    So if you called readOnlyMethod() and pass in any Object, a clone of the Object will be taken. The clone uses the same name as the parameter of the method, so there's no risk of accidentally changing the original Object.

提交回复
热议问题