I want to determine if the fields within an object contain any pointer aliasing?
For example:
class A {
A a1;
A a2;
}
A z = new A();
A y = new A();
y.a1 = z;
y.a2 = z;
A x = new A();
x.a1 = y;
x.a2 = z;
// i.e. x has a reference to y and to z, and y has a reference to z
In this example I want to determine that object x contains pointer aliasing since x.a1.a1 == x.a2
The idea I have is to use reflection to iterate the reference fields of the object, and for each field, build a set of references by traversing through each field storing references as I go (i.e. flatten each reference into a set of references). I would then look at the intersection of these sets. Is this a good solution to my question?
If I understand your need correctly, what you need here is an
IdentityHashSet:Since you want equality for the same references, an
IdentityHashSetis what you want; although if you don't implement.equals()or.hashCode(), a "regular"HashSetcan also do the trick.