Imagine I have the following situation:
Test1.java
import java.lang.ref.WeakReference;
public class Test1
{
public WeakReference fieldName;
public init()
{
fieldName = new WeakReference(this);
Test2.setWeakRef(fieldName);
}
}
Test2.java
import java.lang.ref.WeakReference;
public class Test2
{
public static setWeakRef(WeakReference weakRef)
{
//at this point I got weakRef in an other class.. now, how do I get the field name this reference was created with? So that it returns exactly "fieldName", because that's the name I gave it in Test1.java?
}
}
At the location of the comment I received the weak reference created in an other class. How would I retreive the field name that this weak reference was created with, in this case “fieldName”?
Thanks in advance.
The only way would be using reflection. This is true for fields of any type, not only for weak references.
Of course this example works only if you have a single
WeakReferencefield inTest1.Update: In case you have multiple reference fields, you need access to the object itself, in order to get and compare the actual value of a specific field with the value received. Like in this modified code example:
Note that exception handling is left out for the sake of simplicity.