Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard class which wraps a reference and provides a getter and setter?

Tags:

java

wrapper

Sorry for the stupid question.

I'm very sure, that the Java API provides a class which wraps a reference, and provides a getter and a setter to it.

class SomeWrapperClass<T> {
    private T obj;

    public T get(){ return obj; }

    public void set(T obj){ this.obj=obj; }
}

Am I right? Is there something like this in the Java API?

Thank you.

Yes, I could write it y myself, but why should I mimic existing functionality?

EDIT: I wanted to use it for reference parameters (like the ref keyword in C#), or more specific, to be able to "write to method parameters" ;)

like image 604
ivan_ivanovich_ivanoff Avatar asked Feb 28 '23 10:02

ivan_ivanovich_ivanoff


2 Answers

There is the AtomicReference class, which provides this. It exists mostly to ensure atomicity, especially with the getAndSet() and compareAndSet() methods, but I guess it does what you want.

like image 66
Avi Avatar answered Apr 29 '23 06:04

Avi


When I started programming in Java after years of writing C++, I was concerned with the fact that I could not return multiple objects from a function.

It turned out that not only was it possible but it was also improving the design of my programs.

However, Java's implementation of CORBA uses single-element arrays to pass things by reference. This also works with basic types.

like image 22
Maurice Perry Avatar answered Apr 29 '23 04:04

Maurice Perry