Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java private static final String [] how to use in other methods

I’m new to Java and cannot really understand how to use private static final String[] in other classes.

I have this String[] that I want to access in another class.

private static final String[] NAMES = new String[] {...}
  1. I tried to add @Getter to it, but it still doesn’t pass the check with an error:
    Public static ....getNAME() may expose internal representation by returning ClassName.NAMES
  2. I tried creating a public clone, but I read that it’s not a very good approach.

If I want to use a @Getter, how should I do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Or if I want to expose a public String[] what would be the right way to do?

>Solution :

I agree with RealSkeptic’s suggestion that you can have getter that can return copy :

private static final String[] NAME = new String[] { "Test","Test1" };

public String[] getName() { 
    return Arrays.copyOf(ClassName.NAME, ClassName.NAME.length);
}

And then, in another class, you can use this method to access elements of array. Here ClassName is name of class you have used for declaring this array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading