老师检查作业

来源:3-4 自由编程

慕雪6185030

2020-01-17 09:07:43

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;

}

public void display() {

System.out.println("商品信息");

}

@Override

public String toString() {

return "Goods [id=" + id + ", name=" + name + ", price=" + price + ", desp=" + desp + "]";

}

       

}

package com.imooc.reflect.test;


import java.lang.reflect.Constructor;


import org.junit.Test;


public class ConstructorGoods {

           @Test

           /**

         * 获得无参构造方法 

         */

           public void demo1() throws Exception {

        //获得类的字节码文件对应的对象:

           Class class1 =Class.forName("com.imooc.reflect.test.Goods");

               Constructor c =class1.getConstructor();

               Goods goods =(Goods) c.newInstance();

//               goods.display();

           }

           /**

            * 获得有参的构造方法

            * @throws Exception 

            * 

            */

           @Test

           public void demo2() throws Exception {

           Class class1 =Class.forName("com.imooc.reflect.test.Goods");

               Constructor c=class1.getConstructor(int.class,String.class,Float.class,String.class);

               Goods goods =(Goods) c.newInstance(1,"手机",2000f,"存储容量32G,黑色");

             System.out.println(goods);

           }

           

}


写回答

1回答

好帮手慕阿满

2020-01-17

同学的代码完成的不错,继续加油。

祝:学习愉快~

0

0 学习 · 8016 问题

查看课程