0

This is probably a very silly way to go about things, but say we had a class with lots of Fields that were components, how would one go about adding them in a for each loop with reflection?

Here is what I've tried so far (though it is obviously doomed to fail):

for(Field bits: this.getClass().getDeclaredFields()){
            try {
                this.add((Component)Class.forName(bits.getName()).newInstance());
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Each of the fields is not a class so doing the above will not work, but I have defined what they are, and they should exist at runtime.

How should I be doing this?

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
  • don't do that Reflection returns only declared Fields, but could be possible modify the value or properties – mKorbel Jun 20 '13 at 15:31
  • each of Fields can representing compiled Object, you can to [simple to change whatever properties of their value on runtime](http://stackoverflow.com/questions/6629995/test-if-a-class-contains-an-instance-variable-based-on-its-name), its proper way for testing purposer or intentional hacking in compiled code – mKorbel Jun 20 '13 at 15:40

1 Answers1

1

You try to create a class from a field name, so it won't work.

bits.getName() returns something like "myHelloWorldLabel" and not javax.swing.JLabel.

You can either add the value of the field bits.get(this) or create a new object from the class bits.getDeclaringClass().newInstance().

I would also add a check that the class extends JComponent.

Anthony
  • 1,245
  • 1
  • 16
  • 15