Search code examples
javaclassnullpointerexceptionfieldgettype

To list all the fields of a class and put them in a list if they match a desired type


The title is quite confusing, but what i want to achieve is calling a method to all (swing) buttons / labels in my class. (to make them all look similar)

Something a bit like this:

for(Button btn: components)
  btn.setThisTheme();

where components[] is a array of JComponent-s. So far i have tried this:

    // at beginning of class
    private LinkedList<JComponent> components = new LinkedList<>();
    private Field[] fields = ToDo.class.getDeclaredFields().length;


   // in constructor
   for (Field field: fields) {
            if(field.getType() == JComponent.class) { 
                components.add(field); // how to do this? 
// field is a Field and i need to convert it into the variable it represents...
            }
        }

Solution

  • You are creating an array of nulls.

    private Field[] fields = new Field[ToDo.class.getDeclaredFields().length];
    

    You should be able to use the array returned by getDeclaredFields directly.

    private Field[] fields = ToDo.class.getDeclaredFields();
    

    Almost certainly you can do what you want to do better without reflection.