java - 没有参数的getConstructor

标签 java getconstructor

对于没有参数的构造函数,我似乎无法使用 getConstructor

我不断收到以下异常:

java.lang.NoSuchMethodException: classname.<init>()

代码如下:

interface InfoInterface {
    String getClassName();
    String getMethodName();
    String getArgument();
}

class asa implements InfoInterface {
    @Override
    public String getClassName() {
        return ("jeden");
    }
    @Override
    public String getMethodName() {
        return ("metoda");
    }
    @Override
    public String getArgument() {
        return ("krzyk");
    }
}

class Jeden {
    Jeden() {
        System.out.println("konstruktor");
    }

    public void Metoda(String s) {
        System.out.println(s);
    }
}

class Start {
    public static void main(String[] argv) {
        if (argv.length == 0) {
            System.err.println("Uzycie programu: java Start nazwa_klasy nazwa_klasy2...");
            return;
        }

        try {
            for (int x = 0; x < argv.length; x++) {
                Class<?> c = Class.forName(argv[x]);
                InfoInterface d = (InfoInterface) c.newInstance();
                String klasa = d.getClassName();
                String metoda = d.getMethodName();
                String argument = d.getArgument();

                Class<?> o = Class.forName(klasa);
                // o.newInstance();

                Constructor<?> oCon = o.getConstructor();
                System.out.println("ASD");
                Class<?> p = (Class<?>) oCon.newInstance();
            }
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}

o.newInstance(); 打印 "konstruktor" 没有问题。

最佳答案

当你阅读 javadoc of .getConstructor() 时,问题就很清楚了。 :

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

强调我的。

在您的代码中,构造函数不是公开的!

例子:

// Note: class is NOT public -- its default constructor won't be either
final class Test
{
    public static void main(final String... args)
        throws NoSuchMethodException
    {
        // throws NoSuchMethodException
        Test.class.getConstructor();
    }
}

强制性 link to an SO answer这也给出了 JLS 引用。特别要注意,默认构造函数具有与类相同的访问修饰符。

关于java - 没有参数的getConstructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27579783/

相关文章:

java - 为一组具有相同方法但不实现相同接口(interface)的类编写通用代码的惯用方法是什么?

java - 在方法中调用方法?在这种情况下它是如何工作的? ( java )

java - Java中的循环链表实现

Java - getConstructor()?

java - getConstructor() 在被 Class 类型变量调用时返回 NoSuchMethodException

Java反射(reflect)getConstructor NoSuchMethodException错误

java - 如何在Mule ESB消息流中添加要上传的文件?

java - libGDX:在特定时间后删除迭代器