0

I want to use getFields() to retrieve public fields in a class but this is not working, the lenght of the array is always 0. Do I need to use getters or getDeclaredFields() ?

Field[] fields = gameClass.getFields();

The class contained in gameClass :

public class Solitaire {
public Board board = new Board("Board1", "");
public Layout layout = new Layout();
public Player player = new Player();}

Here how the class is loaded into gameClass : Load a class in a jar just with his name

Cœur
  • 37,241
  • 25
  • 195
  • 267
Spooky
  • 315
  • 1
  • 3
  • 12

1 Answers1

0

I am doing the same thing -

Solitaire gameClass = new Solitaire();
Class gclass = gameClass.getClass();
Field[] fields = gclass.getFields();

And it's working perfectly for me :)

Entire test class -

import java.lang.reflect.Field;

public class Test {

    public static void main(String args[]) {

    Solitaire gameClass = new Solitaire();
    Class gclass = gameClass.getClass();
    Field[] fields = gclass.getFields();

    for (int i = 0; i < fields.length; i++) {
        System.out.println("field: " + fields[i]);
        }
    }
}

class Solitaire {

    public Solitaire a;
    protected String b;
    public String c;

    public Solitaire() {
    }
}
Kartic
  • 2,935
  • 5
  • 22
  • 43
  • Is the fact that I don't declare a constructor in solitaire a problem ? – Spooky Nov 15 '14 at 23:28
  • no, getFields() is supposed to return all public fields on the class (not private or package-protected though). It does not need a constructor which is for constructing object instances of the class, it needs only access to the class object. – marcelv3612 Nov 15 '14 at 23:30
  • Can you try using getDeclaredFields() and see what that returns? – marcelv3612 Nov 15 '14 at 23:31
  • Constructor declaration is not required actually. Are you sure, at least one field is public? – Kartic Nov 15 '14 at 23:33
  • It works, I don't know why this was not working, but it work and I have a new problem ... – Spooky Nov 15 '14 at 23:42
  • (surprising emoticon) Good luck :) – Kartic Nov 15 '14 at 23:45