3-4 自由编程
来源:3-4 自由编程
csm032
2020-04-26 12:38:39
package com.imooc.reflect.test;
public class Goods {
private int id;
private String name;
private float price;
private String desp;
public Goods() {
super();
// TODO Auto-generated constructor stub
}
public Goods(int id, String name, float price, String desp) {
super();
this.id = id;
this.name = name;
this.price = price;
this.desp = desp;
}
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getDesp() {
return desp;
}
public void setDesp(String desp) {
this.desp = desp;
}
@Override
public String toString() {
return "Goods [id=" + id + ", name=" + name + ", price=" + price + ", desp=" + desp + "]";
}
public void display() {
System.out.println("商品信息");
}
}
package com.imooc.reflect.test;
import java.lang.reflect.Constructor;
import org.junit.Test;
public class ConstuctorTest {
//无参构造方法调用display
@Test
public void demo1() throws Exception {
Class class1=Class.forName("com.imooc.reflect.test.Goods");
Constructor c=class1.getConstructor();
Goods g=(Goods) c.newInstance();
g.display();
}
//有参构造方法调用display
@Test
public void demo2() throws Exception {
Class class2=Class.forName("com.imooc.reflect.test.Goods");
Constructor c=class2.getConstructor(int.class,String.class,float.class,String.class);
Goods g=(Goods) c.newInstance(1,"手机",1999,"小米黑色");
System.out.println(g);
}
}1回答
好帮手慕柯南
2020-04-26
同学你好!
完成的不错,加油!祝学习愉快~
相似问题