user482594
user482594

Reputation: 17476

How can I return either read-only access to a returned variable, or write access to it?

In below class, Store class has exactly 1 fruit as a field variable.

I want Store class to do the following two things. One is returning the fruit's data only with read access, and the other is returning the fruit's data with the write access. The data returned has type ByteBuffer.

For example, if someone get the ByteBuffer through getRead, I don't want ByteBuffer to be modified at all. However, if someone access ByteBuffer through getWrite, then I am allowing him to modify the contents of memory pointed by ByteBuffer.

class Fruit {
    private ByteBuffer data;
    public ByteBuffer getData(){
        return data;
    }
}
class Store {
    Fruit p;
    public ByteBuffer getRead(){
        return p.getData();
    }

    public ByteBuffer getWrite(){
        return p.getData();
    }
}

Is there anyway that I can control this access privilege in Java when I am using ByteBuffer? Or, should I have 2 variables in Fruit class that has the same value but does the different thing?

Upvotes: 0

Views: 228

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

In this particular case it's really easy using asReadOnlyBuffer:

public ByteBuffer getRead(){
    return p.getData().asReadOnlyBuffer();
}

In general, there has to be some sort of wrapping object (as there is here) - Java doesn't have the concept of a read-only "view" on an object from a language point of view; it has to be provided by code which prevents any mutations.

Upvotes: 6

Related Questions