Java getting array's name | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Java getting array's name

Hello programmers! Is it possible to get the array's name in java? For example Int[] age = {12, 13, 14, 15}; System.out.println(age.getName());//something like this //[Excepted Output]: age ____________________________ Why I want this? I have 2d object array, where I stored all my arrays in it... Now Im trying to get that array's name just by calling it Like _________________________________ Object [][] student = {array1, array2, array3}; System.out.println(student[2].getName()); //Excepted Output]: array2 Thank you 😊! Happy coding!

20th Apr 2020, 2:18 PM
KingDaniel2004
KingDaniel2004 - avatar
5 Answers
+ 6
If your variable is a field you can use getDeclaredFields() on the class and then on the corresponding field getName(). But as Avinesh stated if you need to use reflections it's almost always a hint that your design isn't the best approach. You should try to refactor the code to avoid the reflection.
20th Apr 2020, 8:47 PM
Tashi N
Tashi N - avatar
+ 3
Lily Mea yeah I got it... But what about my 2nd example? It wont work there Thanks!
20th Apr 2020, 2:48 PM
KingDaniel2004
KingDaniel2004 - avatar
+ 3
Avinesh oh thanks!
20th Apr 2020, 4:23 PM
KingDaniel2004
KingDaniel2004 - avatar
+ 2
Getting an array name is not possible in your first example. In your second example, you are again trying to access the name of the array which is again not possible. The Reflection API might be helpful but is not recommended to use. Trying to print a reference variable will print 'ClassName@HashCode' and you can probably override the toString() to get a result according to your need.
20th Apr 2020, 3:26 PM
Avinesh
Avinesh - avatar
+ 1
looking at this is kinda weird,because if u can get the arrays name like this age.getName() = age then,in order to get the array's name,u need the array's name.. got it?
20th Apr 2020, 2:26 PM
durian
durian - avatar