0

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?

13
  • 8
    Member variables are not polymorphic in Java (whether static or non-static). The best you could do is indeed use reflection, but there's probably a better way to achieve whatever the overall goal is here. Commented May 26, 2014 at 22:01
  • They're not polymorphic? Commented May 26, 2014 at 22:01
  • No, only non-static methods are. Commented May 26, 2014 at 22:02
  • 1
    No, they're not. You have to change your design. Commented May 26, 2014 at 22:02
  • 3
    How about defining an Interface HasI with a getI() method and making A, B, and C implement HasI? Your compare will be public int comapre(HasI a, HasI b) Commented May 26, 2014 at 22:06

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

3 Comments

The compiler should complain about that compiler won't complain about it, it will show a warning and sadly we programmers tend to ignore warnings because we only care for errors :)
by complain I mean show a warning. I will edit to make it more explicit.
Compiler complain is usually known as a compiler error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.