1

I've got an interface:

public interface Interface {
public static final String FIELD1 = "BAR";
public static final String FIELD2 = "FOO";
.........
}

I'm trying to read the field name via reflection using this code:

    Field[] fields = Interface.class.getFields();
    for (Field f : fields) {
          ............
    }

The problem is that the array has always length zero. Why?

Edit: I'm using proguard and I think the problem is related with interface obfuscation.

greywolf82
  • 21,813
  • 18
  • 54
  • 108
  • Perhaps [Reading only static fields in Java](http://stackoverflow.com/questions/3422390/retrieve-only-static-fields-declared-in-java-class) helps – Mick Mnemonic Oct 10 '15 at 08:17
  • It works fine for me with the exact code you've shown. If you can reproduce this, please show it in a short but complete program. – Jon Skeet Oct 10 '15 at 08:22
  • what java version are you using? – flo Oct 10 '15 at 08:38

2 Answers2

1

I am running the same code as you have provided and able to print the name of the fields from the interface.

import java.lang.reflect.Field;

public class Prop {
  public static void main(String[] args)
  {
    Field[] fields = Interface.class.getFields();
    for (Field f : fields) {
      System.out.println(f.getName());
    }
  }
}

interface Interface {
  public static final String FIELD1 = "BAR";
  public static final String FIELD2 = "FOO";
}

Ouput:

FIELD1  
FIELD2
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
  • 3
    This should be a comment, not an answer - you're basically just saying you can't reproduce the problem. I agree - neither can I - but it means the question shouldn't be answered without editing. – Jon Skeet Oct 10 '15 at 08:25
  • I agree with you. I will remove it. – YoungHobbit Oct 10 '15 at 08:27
  • I don't agree with either of you "You're wrong" is just as much an answer as any other. – user207421 Oct 10 '15 at 08:29
  • @EJP The above code works. That was my intend to show to the OP. So what is your take on this answer? – YoungHobbit Oct 10 '15 at 08:53
  • @EJP: It's not useful to anyone. If the question was along the lines of "My understanding of polymorphism is that (xyz)" then "No, you're wrong, it's like this..." is useful to future readers. When the question shows some code and claims it behaves one way when it actually behaves a different way, it provides no value to the site - and an "answer" saying "No it doesn't" provides no value as an answer either. What *does* provide value is the OP editing the question to actually show the code that misbehaves. – Jon Skeet Oct 10 '15 at 08:54
1

Simply use:

Field[] fields = Interface.class.getDeclaredFields();

Instead of :

Field[] fields = Interface.class.getFields();

It worked fine for me!

DiLDoST
  • 335
  • 3
  • 12