How can you extend Java to introduce passing by reference?

前端 未结 10 2259
天命终不由人
天命终不由人 2020-12-24 06:19

Java is pass-by-value. How could you modify the language to introduce passing by reference (or some equivalent behavior)?

Take for example something like

<         


        
10条回答
  •  鱼传尺愫
    2020-12-24 06:58

    The usual idiom I've seen for pass-by-reference in Java is to pass a single-element array, which will both preserve run-time type-safety (unlike generics which undergo erasure) and avoid the need to introduce a new class.

    public static void main(String[] args) {
        String[] holder = new String[1];
    
        // variable optimized away as holder[0]
        holder[0] = "'previous String reference'";
    
        passByReference(holder);
        System.out.println(holder[0]);
    }
    
    public static void passByReference(String[] someString) {
        someString[0] = "'new String reference'";
    }
    

提交回复
热议问题