简体   繁体   English

具有构造函数的newInstance()类

[英]Class newInstance() with Constructor

The following code is returning null: 以下代码返回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? 为什么返回null,我该如何解决?

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;
    }

It's returning null as its silently failing in the exception block. 它返回null因为它在异常块中无提示地失败了。 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. 主要问题在于,您需要使用传入的构造函数参数相对应的匹配类类型参数 ,而不是特定的JComponent本身的类型来定位正确的构造函数。 ie JTextField(String) 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM