Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to call <em>getDeclaredFields()</em> on class A itself and then use reflection to set the field accessible thusly</p> <pre><code>import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Test{ public static void main(String args[]){ B someB = new B(); B otherB = new B(); Field uniqueField = null; for(Field f : A.class.getDeclaredFields()){ if(!Modifier.isFinal(f.getModifiers())) continue; if(!UNIQUE.class.isAssignableFrom(f.getType())) continue; uniqueField = f; break; } if(null == uniqueField) throw new NullPointerException(); uniqueField.setAccessible(true); try{ System.out.println(uniqueField.get(someB) != uniqueField.get(otherB)); }catch(IllegalArgumentException | IllegalAccessException e){ throw new RuntimeException(e); } } } class UNIQUE{ } class A{ private final UNIQUE u; private final String someOtherMember = ""; A(){ u = new UNIQUE(); } } class B extends A{ } </code></pre> <p>if you don't have a direct reference to class A or if there is more than one superclass that has this unique field then you can loop over each one (making sure to check at each stop that you didn't climb all the way to object) by doing something more like this in the example above</p> <pre><code> Class&lt;?&gt; clazz = someB.getClass(); classClimb: do{ for(Field f : clazz.getDeclaredFields()){ if(!Modifier.isFinal(f.getModifiers())) continue; if(!UNIQUE.class.isAssignableFrom(f.getType())) continue; uniqueField = f; break classClimb; } }while(Object.class != (clazz = clazz.getSuperclass())); if(null == uniqueField) throw new NullPointerException(); uniqueField.setAccessible(true); try{ System.out.println(uniqueField.get(someB) != uniqueField.get(otherB)); }catch(IllegalArgumentException | IllegalAccessException e){ throw new RuntimeException(e); } </code></pre> <p>Remember that in that case you'll have to either do the reflection on every single object, do some caching, or have multiple reflection sites that are specific to each expected superclass.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload