saneGuy
saneGuy

Reputation: 121

Is there a way to get name of an array in java?

String[] names = {"abc"};

for this array can we retrieve the array's name names ?

We can get the class of the array, but can we get the name of the array?

Upvotes: 2

Views: 5784

Answers (2)

topher217
topher217

Reputation: 1357

You could achieve similar functionality by creating your own class with a attribute called "name". The simplest example:

MyArray myArray = new MyArray();


class MyArray{
    public String name = "myArray";
    public String[] names = {"Name1", "Name2", "Name3"};
}

If you wanted to have a different name for each instance make a constructor that accepts a name as an input parameter:

MyArray myArray = new MyArray("myCustomName");

class MyArray{
    public String name = "myArray";
    public String[] names = {"Name1", "Name2", "Name3"};

    public MyArray(String name){
        this.name = name;
    }
}

Upvotes: 0

D.B.
D.B.

Reputation: 4713

As a general rule no, it's not possible. However, there are some circumstances when you can obtain the name of a variable through reflection:

  1. When the variable is a field of a class - see this link and
  2. When the variable is a parameter of a method - see this related question

Upvotes: 4

Related Questions