0

Basically I got told that I shouldn't have public methods returning Arrays for "future" security purposes. Instead they should be private, and if I wanna return an Array it would have to be some kind of copy in another method.

This is how it looks now..

public Object[] ownedObject() {

    return objectArr;
}

If I make this private the class that needs it doesn't recognize the method above.

Thing is I need to use the contents in that Array in said, other class, and the total project, as I have it right now with 5 different classes, works (with the returning Array-methods set to Public and not private).

Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • 1
    Does this answer your question? [Java: Copy array of non-primitive type](https://stackoverflow.com/questions/1366303/java-copy-array-of-non-primitive-type) – kaya3 Feb 04 '20 at 18:12

1 Answers1

2

As you are concerned with security aspect of this problem you might want to distinguish between shallow copy and deep copy of the array. If your array contains mutable objects you probably need a deep copy of every single element in the array to ensure that state is not leaking from your object.

Assuming that you array is of type MyType with a copy constructor:

public MyType[] ownedObject() {
    MyType[] copyArr = new MyType[objectArr.lenght];
    for (int i = 0; i < objectArr.lenght; i++) {
        copyArr[i] = new MyType(objectArr[i]);
    }
    return copyArr;
}

There are also other ways to deep copy an object.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • Ah I see! It is indeed a copy constructor. But it has the parameters [String, String, int, int] so it won't take [i] as parameter when making the copyArr. Which gives me some kind of problems. – Oskar Sandell Feb 04 '20 at 20:15
  • Alternatively, would there be any reasonable arguments for the original method to STAY public, and if so what would the most considerable risks be? – Oskar Sandell Feb 04 '20 at 20:21