2
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?

Gherbi Hicham
  • 2,416
  • 4
  • 26
  • 41
saneGuy
  • 121
  • 1
  • 3

2 Answers2

4

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
Community
  • 1
  • 1
D.B.
  • 4,523
  • 2
  • 19
  • 39
  • If the class file has been obfuscated, the name of the variable is likely to be non informative. – emory Jun 20 '16 at 00:58
0

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;
    }
}
topher217
  • 1,188
  • 12
  • 35