-1

I tried to simulate pass-by-ref in java by passing an array of size 1 that contains the value to a corresponding method.

The source:

    public static void test(String... a) {
    a[0] = new String("bar");
}

public static void main(String[] args) throws Exception {

    String a = "foo";
    test(a);
    System.out.println(a);
}

The value is still "foo" - why? I use JDK version 15.0.1.

NHSH
  • 69
  • 7

2 Answers2

4

First, the new String is pointless. Don't do that.

public static void test(String... a) {
    a[0] = "bar";
}

Second, in order to pass an array by reference, you must pass an array. Like,

public static void main(String[] args) throws Exception {
    String[] a = {"foo"};
    test(a);
    System.out.println(a[0]);
}

Outputs

bar

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Ah, okay... Hm, this is not satisfying: What I am trying to archive is substituting any arbitary object passed to a method (lets call it createProxy(Object)) by an instance of corresponding proxy-class, that is subclass of the object's class (which will be genereated at runtime with javassist).. Hibernate does this kind of thing by .save(Object) -> The object automatically becomes an instance of the proxy-class, without passing an array to the .save-Method. How did they do it - if I might ask here? – NHSH Nov 29 '20 at 00:26
  • @ChezBorz Can you show us an example where hibernate would change the object to an instance of the proxy class? – Progman Nov 29 '20 at 00:30
  • 1
    @Progman Oh, now I see it - the object is substituted by a proxy-instance AFTER the programmer calls the get()-Method of hibernate's session-factory, this is, let's say we persisted an object of the class "A", if we now call (A)session.get(A.class, id), the object that will be returned most probably won't be an instance of A, but an instance of a proxy-class of A... I guess. Interesting. Thanks for asking, because otherwise I probably wouldn't examine it again. – NHSH Nov 29 '20 at 00:40
2

This

public static void main(String[] args) throws Exception {
    String a = "foo";
    test(a);
    System.out.println(a);
}

is effectively the same as this:

public static void main(String[] args) throws Exception {
    String a = "foo";
    String[] temp = { a }; 
    test(temp);
    System.out.println(a);
}

and thus 'a' is not changed.

user14644949
  • 321
  • 1
  • 3
  • Yes, you are right, but this is exactly what I tried to achieve, but apperently, this is not how things work, as Elliot Frisch pointed out. – NHSH Nov 29 '20 at 00:29