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?

8
  • 2
    what are you trying to achieve? Commented Jun 20, 2016 at 0:38
  • 2
    A key part of understanding Java is learning the difference between an object, and the references to it. Only references have names; the object itself has no name. Commented Jun 20, 2016 at 0:39
  • 3
    How would you reference it to get the name, if not by name? Commented Jun 20, 2016 at 0:40
  • 3
    The short answer to your question is "no." The long answer is "nooooooooooo." Absolutely no way, if it's a local variable. Commented Jun 20, 2016 at 0:43
  • 2
    What if you have two array variables, arrayA and arrayB, and both reference the same array object -- what would you say the "name" of the array object is? It doesn't make sense since (as @MarkPeters aptly puts), objects don't have "names". Commented Jun 20, 2016 at 0:48

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

If the class file has been obfuscated, the name of the variable is likely to be non informative.
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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.