Dean
Dean

Reputation: 13

How to get the object name of class?

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?

Upvotes: 1

Views: 1182

Answers (3)

Droo
Droo

Reputation: 3205

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.

Upvotes: 1

aldrin
aldrin

Reputation: 4572

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.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994817

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".

Upvotes: 2

Related Questions