Can I test which one owner class Child's instance.
$ cat Child.java
public class Child
{
public Child(){}
//how to Know which owner the object,ParentA or ParentB?
public void testParent()
{
}
}
$ cat ParentA.java
public class ParentA
{
Child a;
}
$ cat ParnetB.java
public class ParentB
{
Child b;
}
$
If you have an object, there is no way to find out about what variables refer to it. Your question doesn't make much sense, maybe you could explain why you need to know this (whatever it is)?
The easiest way is to give Child a reference to the object that created it.
public class Child() {
private Object parent;
public Child(Object obj) {
parent = obj;
}
public void testParent() {
System.out.println("Parent is " + parent.getClass());
}
}
public class ParentA {
Child a = new Child(this);
}
public class ParentB {
Child b = new Child(this);
}
in java ,it has reflect package that can test a class has some fields or some methods. i just want to know, can i reverse it or not ? nothing to use. thank you!
you may misunderstand the concept of object variables, they are reference to an object. an object may have many references from many other objects, and you can't tell the object itself belongs to what object. in your case, the child actually is a reference rather than an object, and the reference is a value, it can just stay inside the you-called parent objects, and any assignment or method return value is a copy of the reference rather than itself. so it does not make any sense to find its parent.
References point only one way. It's very easy to determine the object that a reference points to, just dereference the reference.
It's hard to determine the references that point to an object -- you have to go through all references and compare them to a reference to the object.