Anubian Noob
Anubian Noob

Reputation: 13596

Get static field from instance

I have a class with multiple subclasses:

class A {

    static int i = 5;
}

class B extends A{

    static int i = 6;
}

class C extends A {

    static int i = 7;
}

I'm trying to write a comparator that takes two A's and compares them based on their values of i. I'm stuck at:

public int compare(A a1, A a2) {

}

Neither a1.i nor a1.class.getField("i").getInt(null); work.

How can I get the value of the static field from the object?

Upvotes: 0

Views: 1794

Answers (1)

njzk2
njzk2

Reputation: 39397

a1.i

Because a1 is declared a A, it is equivalent to A.i. The compiler should tell you about that with a warning. Most IDE will do that to and give a little message about what to do about it.

a1.class.getField("i").getInt(null);

Can't work because class is static.

You can use

a1.getClass().getDeclaredField("i").getInt(null);

getClass is an instance method to get the class of an object. getDeclaredField will return all fields, while getField will only return the public ones.

Upvotes: 2

Related Questions