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;

}

$

[387 byte] By [Dezhong_ye] at [2007-9-26 2:16:25]
# 1
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)?
DrClap at 2007-6-29 9:14:50 > top of Java-index,Core,Core APIs...
# 2

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);

}

nerd2004 at 2007-6-29 9:14:50 > top of Java-index,Core,Core APIs...
# 3
The first line should have beenpublic class Child {
nerd2004 at 2007-6-29 9:14:50 > top of Java-index,Core,Core APIs...
# 4
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!
Dezhong_ye at 2007-6-29 9:14:50 > top of Java-index,Core,Core APIs...
# 5

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.

andy.g at 2007-6-29 9:14:50 > top of Java-index,Core,Core APIs...
# 6

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.

schapel at 2007-6-29 9:14:50 > top of Java-index,Core,Core APIs...