对于没有参数的构造函数,我似乎无法使用 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/