Is there a way to create a public method inside a class that can return the variable name used to declare an instance of that class outside that class?
A very similar question has been posted 10 years ago and the answer was that there is no such way. I am wondering if there is a possible way that has been developed over the time.
Here is an example of the Class:
import java.lang.reflect.Field;
import java.util.ArrayList;
public class Class {
private ArrayList<Array> elements; //Array is some other class
public Class() {
elements = new ArrayList<>();
}
public String getInstanceName() {
Field[] fields = this.getClass().getDeclaredFields();
return fields[0].getName(); // returns "elements"
}
So, outside the class I would declare the instance of Class and treat it as value in a HashMap
public class SomeOtherClass {
private HashMap<String, Class> classes
classes = new HashMap<>();
Class abc = new Class();
String someKey = "Abc";
classes.put(someKey, abc);
and the statement below would desirably return the string 'abc'
System.out.println(classes.get(someKey).getName());
However the print statement would return the String "elements"