简体   繁体   English

为什么没有给我这种方法异常

[英]why it is giving me no such method exception

import java.lang.reflect.Constructor;

class tr1
{
    public static void main(String[] args) {
        try {
            if(args.length<1)
                throw(new Exception("baby its wrong"));
            Class s= Class.forName(args[0]);
            Constructor c=s.getDeclaredConstructor(int.class,char.class,String.class,String.class);
            Object o=c.newInstance(Integer.parseInt(args[1]),args[2].charAt(0),args[3],args[4]);
            System.out.println("description of object "+o);

        } catch (Exception e) {
            System.out.println(e);  
        }
    }   
}
class A
{
    public A(int a,char c,String ...strings){
        System.out.println(a);
        System.out.println(c);
        for(String q:strings)
        {
            System.out.println(q);
        }
    }   

}

why this code is giving me nosuchmethod exception? 为什么这段代码给了我nosuchmethod异常? any solution for it? 有什么解决办法吗?

Because an ellipsis is syntactic sugar for an array. 因为省略号是数组的语法糖。

You should: 你应该:

s.getDeclaredConstructor(int.class, char.class, String[].class);

(and as @JonSkeet mentions in his answer, you should also make your third argument an array in the .newInstance() invocation) (正如@JonSkeet在回答中提到的那样,您还应该在.newInstance()调用.newInstance()第三个参数设置为数组)

why this code is giving me nosuchmethod exception? 为什么这段代码给了我nosuchmethod异常?

Because you don't have a constructor with the parameters you've requested: 因为您没有具有所要求参数的构造函数,所以:

(int, char, String, String)

You only have a constructor with these parameters: 您只有具有以下参数的构造函数:

(int, char, String[])

where the String[] is a varargs parameter. 其中String[]是varargs参数。

The fact that there's a varargs parameter is basically a compile-time artifact. 有varargs参数的事实基本上是编译时工件。 You can detect this at execution time using Constructor.isVarArgs() but that doesn't change the signature of the constructor. 您可以在执行时使用Constructor.isVarArgs()进行检测,但这不会更改构造函数的签名。

any solution for it? 有什么解决办法吗?

Use the existing constructor instead :) 使用现有的构造函数:)

Constructor c = s.getDeclaredConstructor(int.class, char.class, String[].class);
Object o = c.newInstance(Integer.parseInt(args[1]),
                         args[2].charAt(0),
                         new String[] { args[3], args[4] });

That creation of a String[] to pass to the constructor is basically what the compiler would do for you if you called 传递给构造函数的String[]的创建基本上就是编译器为您执行的操作

new A(Integer.parseInt(args[1]), args[2].charAt(0), args[3], args[4])

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

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