How to create IN OUT or OUT parameters in Java

前端 未结 3 471
[愿得一人]
[愿得一人] 2021-01-17 18:05

In PL/SQL (or many other languages), I can have IN OUT or OUT parameters, which are returned from a procedure. How can I achieve a similar thing in Java?

I know this

相关标签:
3条回答
  • 2021-01-17 18:34

    My question would be: Why doesn't method return something? Rather than setting an in/out argument?

    But assuming you absolutely, positively must have an in/out argument, which is a whole different question, then the array trick is fine. Alternately, it's not less clumsy, but the other way is to pass in an object reference:

    public class Foo {
        private String value;
    
        public Foo(String v) {
            this.value = v;
        }
    
        public String getValue() {
            return this.value;
        }
    
        public void setValue(String v) {
            this.value = v;
        }
     }
    
     // ....
     public void method(String in, Foo inOut) {
         inOut.setValue(in);
     }
    

    (Or, of course, just make value public.) See? I said it wasn't less clumsy.

    But I'd ask again: Can't method return something? And if it needs to return multiple things, can't it return an object instance with properties for those things?

    Off-topic: This is one of the areas where I really like the C# approach. One of the arguments against in/out arguments is that they're unclear at the point where you're calling the function. So C# makes you make it clear, by specifying the keyword both at the declaration of the function and when calling it. In the absense of that kind of syntactic help, I'd avoid "simulating" in/out arguments.

    0 讨论(0)
  • 2021-01-17 18:47

    Java copies anything you pass as an argument. If you pass a primitive, inside method you have copy of that primitive, and no modifications will affect the actual variable outside method. If you pass object, you pass copy of reference, which actually references to the original object. This is the way how you can propagate modifications to the context of something that called the method - by modifying the state of the object that the reference is 'pointing' to. See more on this: Does Java Pass by Value or by Reference?

    0 讨论(0)
  • 2021-01-17 18:57

    There's no direct way. Other technique include:

    • Passing a holder object (a bit like your 1-ary array)
    • Using, e.g., an AtomicInteger
    • Passing a more useful object from a business perspective that happens to be mutable
    • A callback to a custom interface for receiving the result

    If you think about it, the array trick is not dissimilar to passing a T* in C/C++

    0 讨论(0)
提交回复
热议问题