0

It's not the first year I use Java for development, but I faced this issue the very first time. I have pretty complex permission module in my system which modifies object I return to the client in accordance with access control list.

To be short, I need to nullify object passed to another function. Here is some code:

public static void main(String[] args) {
    String s = "filled";
    nullify(s);
    System.out.println(s);
    s = null;
    System.out.println(s);
}

public static void nullify(String target) {
    target = null;
}

I understand that s is passed to nullify() by value and when I setting target to null it doesn't affect s. My question is there any way in Java which allows me to set s to null having target?

Thanks.

p.s. I found lots of information about setting variables to null but all of them was related to garbage collection and didn't answer my question.

mr.nothing
  • 5,141
  • 10
  • 53
  • 77
  • No, there isn't. The `target` and `s` variables are unrelated, other than in terms of initial value. – Jon Skeet Feb 18 '16 at 14:21
  • `s` is simply a reference to a string. When you enter `s = null;` or `target = null;` all you're doing is changing what that reference is pointing to. If you actually want to change the data in that particular string then you're going to have to get more low level. Try looking at `Charset` – flakes Feb 18 '16 at 14:24
  • here is a good example http://stackoverflow.com/questions/11146255/create-a-mutable-java-lang-string – flakes Feb 18 '16 at 14:25
  • @flkes Thanks, but in context of what I'm trying to develop I need to set to `null` absolutely abstract objects. It's not only a matter of settings `String` object to `null`. – mr.nothing Feb 18 '16 at 14:27
  • @mr.nothing if you want other objects to see that the object is now null, try using a wrapper. `class MyWrapper{ public Object myobj; }` then pass around the wrapper and work on the object inside. `MyWrapper wrap = new MyWrapper(); wrap.myobj = "myString"; wrap.myobj = null;` – flakes Feb 18 '16 at 14:30

0 Answers0