简体   繁体   中英

Get (access) class from its field

Fairly new to Java as well as SO. Here's my question:

Suppose x is an instance of a Class X. And y is an attribute (field) of X. If I pass "xy" in a function f, is there a way to access x?

Example:

Class Person
{
    public Girl girl; //Girl itself is another class
}

public void function1(Girl g)
{
     //body
}

Person p = new Person();
p.girl = new Girl();
function1(p.girl);

Now, I want to access p in the function. (Something like a "previous" pointer in a linked list).

Looked around and found something called Reflection. But that doesn't help, really. Thanks!

The short answer to your question is no. Unless the Girl object is specifically designed to have a reference to its parent (you see that a lot in GUI objects in java). But that is up to whoever designed the class. Much like your example of a "previous pointer" that relies on the developer implementing a "previous pointer" in the first place. The developer could just as easily have used a singly linked list with no previous pointer.

So in short. It depends on the objects you're using. Reflection is not the answer here. Reflection is more about accessing things via their string names and inspecting members of a class.

Sure you can reference, like a linked list, provided the reference is available. Take a look at this program. Please let me know if I misunderstood your question.

public class Person
{

    String personName;
    static class Girl 
    {
        Person girlParent;
        String girlName;

        public Girl(String name, Person parent)
        {
            girlName = name;
            girlParent = parent;
        }
    }

    public Person(String name)
    {
        personName = name;
    }

    public static void function(Girl girl)
    {
        System.out.println("The girl's name is "+girl.girlName);
        System.out.println("The girl's parent is "+girl.girlParent.personName);
    }

    public static void main(String[] args)
    {
        Person julia = new Person("Julia");
        Girl nancy = new Girl("Nancy", julia);
        function(nancy);
    }
}

The output is

The girl's name is Nancy
The girl's parent is Julia

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM