3-4 自由编程
来源:3-4 自由编程
慕粉2137545909
2019-08-09 16:30:26
Goods.java
public class Goods {
private int id;
private String name;
private double price;
public Goods() {
}
public Goods(int id, String name, double price, String description) {
this.id = id;
this.name = name;
this.price = price;
this.description = description;
}
@Override
public String toString() {
return "Goods{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", description='" + description + '\'' +
'}';
}
public void display() {
System.out.println(this.toString());
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
private String description;
}Test.java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test {
public static void main(String[] args) {
try {
Class c=Class.forName("Goods");
Constructor constructor1=c.getConstructor();
Goods g1= (Goods) constructor1.newInstance();
g1.display();
Constructor constructor2=c.getConstructor(int.class,String.class,double.class,String.class);
Goods g2= (Goods) constructor1.newInstance(1,"手机",1500.0,"可以打电话");
g2.display();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}报错信息
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at Test.main(Test.java:13)
1回答
同学你好!同学添加参数时,使用的是无参构造器创建的实例,所以报错了

同学在传递参数时,使用有参构造器创建的实例即可

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
相似问题