3-4 自由编程

来源:3-4 自由编程

慕的地2082093

2020-03-14 12:03:57

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 ConstructorTest {


@Test

/**

* 获得无参数的构造函数

* @throws Exception

*/

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();

}

@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 g = (Goods)c.newInstance(1,"电风扇",23,"老旧款");

System.out.println(g.toString());

}

}


写回答

1回答

好帮手慕阿莹

2020-03-14

同学你好,同学的代码完成的不错哦,很棒,继续加油!!

如果我的回答解决了你的问题,请采纳,祝学习愉快.

0

0 学习 · 8016 问题

查看课程