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

Time:08-24

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?

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

CodePudding user response:

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.

CodePudding user response:

The String[] you receive in the main method is a special case; it is populated with the arguments entered on the command line when starting java. Typically this data is processed immediately and influences how the program runs. If you want to access this array in other classes, you have options:

  • create an instance of the other class, and pass the array as an argument:

    public static void main(String[] args) {
      OtherClass other = new OtherClass(args);
    
  • create an instance of the main class, set the array as a field and add a getter:

    public class MyApp {
    
      private String[] args;
    
      public static void main(String[] args) {
          MyApp myApp = new MyApp();
          myApp.setArgs(args);
          OtherClass other = new OtherClass(myApp);
      }
    
      public String[] getArgs() { return args;}
      public void setArgs(String[]) { this.args = args;}
    ...
    
    public class OtherClass {
    
       public OtherClass(MyApp myApp) {
           String[] args = myApp.getArgs();
    

It all boils down to the same thing: You have to pass or receive the reference via a constructor or method call.

  • Related