Does Java have something like C#'s ref and out keywords?

后端 未结 7 1526
陌清茗
陌清茗 2020-11-27 03:31

Something like the following:

ref example:

void changeString(ref String str) {
    str = \"def\";
}

void main() {
    String abc = \"abc\";
    chan         


        
7条回答
  •  鱼传尺愫
    2020-11-27 03:56

    Direct answer: No

    But you can simulate reference with wrappers.

    And do the following:

    void changeString( _ str ) {
        str.s("def");
    }
    
    void testRef() {
         _ abc = new _("abc");
         changeString( abc );
         out.println( abc ); // prints def
    }
    

    Out

    void setString( _ ref ) {
        str.s( "def" );
    }
    void testOut(){
        _ abc = _();
        setString( abc );
        out.println(abc); // prints def
    }
    

    And basically any other type such as:

    _ one = new (1);
    addOneTo( one );
    
    out.println( one ); // May print 2
    

提交回复
热议问题