-2

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"

1 Answer 1

0

Not exactly an answer, but anyway...

Even if it were possible, you SHOULD NOT DO IT. The behaviour of an instance should not depend on how it is used. The variable name holding the instance is a property of the instance's user and not the instance. And by the way, which name would you return if the instance is referenced by two variables?

And then, variable naming should not affect a program's behaviour. You should always reserve the possibility of refactoring (your IDE surely has a "Rename variable" refactoring). Having your program reason about variable names breaks that possibility and makes it silently fail when using this (otherwise completely safe) refactoring.

If, in a variable a you need an instance that behaves differently from one in variable b, supply some distiguishing information when constructing the instances.

Better ask yourself why you want to ask the instance about information not belonging to itself, but to its environment (you wouldn't ask a person in which drawer some local administration keeps his files - if important, you'd ask the administration).

Design your software architecture in such a way that the behaviour of an instance only depends on its contents. If you need an information, ask the instance that naturally owns this information. Everything else will only give you headaches.

Sign up to request clarification or add additional context in comments.

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.