1

The following code is returning null:

    private JComponent setupComponent(Class<? extends JComponent> c, Object... constructor) {

        try {
            return c.getConstructor(new Class[] { c.getClass() }).newInstance(constructor);
        }
        catch (Exception e) { }

        return null;
    }

I am calling it here:

    JTextField userText = (JTextField) setupComponent(JTextField.class, "Test");

Why is it returning null and how can I fix it?

nrubin29
  • 1,522
  • 5
  • 25
  • 53
  • `java.lang.NoSuchMethodException: javax.swing.JTextField.(javax.swing.JTextField)` – JHS Jul 04 '13 at 01:14
  • 1
    Never leave a blank `catch` statement. At the very least put `e.printStackTrace()` with a comment saying that that block should never be called. This way when you run into unexpected behavior (such as the exception that's being thrown and you're ignoring), you can figure out why. – Jeffrey Jul 04 '13 at 01:19

2 Answers2

0

You need to use the static version of class.

   private JComponent setupComponent(Class<? extends JComponent> c, Object... constructor) {

        try {
            return c.getConstructor(new Class[] { c}).newInstance(constructor);
        }
        catch (Exception e) { }

        return null;
    }
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

It's returning null as its silently failing in the exception block. Display the stacktrace to show the source of the exception.

The main problem is that you need to use matching class type arguments which correspond to the constructor arguments passed in rather than the type of the specific JComponent itself to target the correct constructor. i.e. JTextField(String)

private JComponent setupComponent
                 (Class<? extends JComponent> c, Object... constructor) {

    // build matching class args    
    Class<?>[] classArgs = new Class[constructor.length];
    for (int i = 0; i < constructor.length; i++) {
        classArgs[i] = constructor[i].getClass();
    }

    try {
        return c.getConstructor( classArgs ).newInstance(constructor);
    } catch (Exception e) {
        e.printStackTrace(); // add this
    }

    return null;
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276