Skip to content
标签
欢迎扫码关注公众号

在 Java 中传递参数引用

今天想在 Java 中传递变量引用到方法时,发现 Java 中没有对应的关键字(类似与 C# 中的 refout)。

网上找到的都是通过包装类的方式来实现这个功能的,这里贴一下 stackoverflow 上的一种比较简明的写法。

包装类(_):

_ 就是类名,通过 g() 方法获取引用,通过 s(t) 方法设置引用。

java
public class _<T> {
    T ref;

    public _(T t) {
        ref = t;
    }

    public T g() {
        return ref;
    }

    public void s(T t) {
        this.ref = t;
    }

    public String toString() {
        return ref.toString();
    }
}

用法示例:

java
public class Test {

    public static void main(String[] args) {
        _<Integer> iByRef = new _<Integer>(1);
        addOne(iByRef);
        System.out.println(iByRef); // prints 2

        _<String> sByRef = new _<String>("Hola");
        reverse(sByRef);
        System.out.println(sByRef); // prints aloH

    }

    // Change the value of ref by adding 1
    public static void addOne(_<Integer> ref) {
        int i = ref.g();
        ref.s(++i);

        // or
        //int i = ref.g();
        //ref.s( i + 1 );

    }

    // Reverse the vale of a string.
    public static void reverse(_<String> otherRef) {
        String v = otherRef.g();
        String reversed = new StringBuilder(v).reverse().toString();
        otherRef.s(reversed);
    }

}

2021-05-13 追记

今天发现编译时报了这个警告,看来最好还是起个有意义的类名比较好:

Warning:(25, 56) java: '_' 用作标识符
(Java SE 8 之后的发行版中可能不支持使用 '_' 作为标识符)

参考

  1. Does Java have something like C#'s ref and out keywords?
  2. Simulating reference with wrappers.

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.