1

I had two Java classes: class A and class B, both in the same package. Now I made two objects of class A inside class B, and now from within class A I want the name of objects of class A declared inside class B.
How do I do that?

1

3 Answers 3

2

One method would be for class B to pass a "name" of the A instance to A's constructor:

public class A {
    public A(String name) {
        this.name = name;
    }
    private final String name;
}

In this way, each instance of A will know the name it's been assigned (by whoever constructed it).

Note that there isn't any way for A to find out the name of the variable that's currently being used to refer to it. This is because reference variables may be assigned at will:

A foo = new A();  // A's name could be considered to be "foo"
A bar = foo;      // now, is A's name "foo" or is it "bar"? (It's both!)
foo = null;       // and now, it's only referred by "bar".
Sign up to request clarification or add additional context in comments.

Comments

1

You could do something like this:

public class NameRetriever {
    public static List<String> retrieveNames(Class<?> ownerClass, Class<?> clazzToFind) {
        List<String> names = new ArrayList<String>();
        for (Field field : ownerClass.getDeclaredFields()) {
            if (field.getType().getName().equals(clazzToFind.getName())) {
                names.add(field.getName());
            }
        }
        return names;
    }
}

NameRetriever.retrieveNames(ClassB.class, ClassA.class);

This would find all member variables of type ClassA contained within the ClassB class. If you wanted to get the values of an instantiated object, you could change the ownerClass parameter to 'Object object' and get the value of the field instead of name.

Comments

0

Do you want the 'name' of the objects or references to the objects? You can have class B constructors register any objects created with class A. If you can provide more information about what you want to do with the class B objects from within class A, then maybe we can answer your question better.

cheers.

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.