麻烦老师看看
来源:3-4 自由编程
shuaiyi
2019-10-16 18:44:05
goods类:
package com.imooc.reflect.zuoye;
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.zuoye;
import java.lang.reflect.Constructor;
import org.junit.Test;
public class GoodsTest {
@Test
/**
* 获得无参构造
* @throws Exception
*/
public void demo1() throws Exception{
Class cl1 = Class.forName("com.imooc.reflect.zuoye.Goods");
Constructor c = cl1.getConstructor();
Goods g = (Goods) c.newInstance();
g.display();
}
@Test
/**
* 获得有参构造
* @throws Exception
*/
public void demo2() throws Exception{
//获得Goods类的对象
Class cl2 = Class.forName("com.imooc.reflect.zuoye.Goods");
//获得Goods类的构造方法
Constructor c1 = cl2.getConstructor(int.class,String.class,Float.class,String.class);
//使用newInstance将方法实例化 并赋值
Goods g1 = (Goods) c1.newInstance(1, "冰箱", 2000.0f, "黑色,对开门");
System.out.println(g1.toString());
}
}1回答
好帮手慕柯南
2019-10-16
同学完成的不错,加油,祝学习愉快~
相似问题