JAVA反射3-4自由编程
这是Goods类的商品信息类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | package com.winking.fanshe; public class Goods { public Goods() { super (); } public Goods( int num, String name, int price, String desp) { super (); this .num = num; this .name = name; this .price = price; this .desp = desp; } private int num; private String name; private int price; private String desp; public int getNum() { return num; } public void setNum( int num) { this .num = num; } public String getName() { return name; } public void setName(String name) { this .name = name; } public int getPrice() { return price; } public void setPrice( int price) { this .price = price; } public String getDesp() { return desp; } public void setDesp(String desp) { this .desp = desp; } @Override public String toString() { return "Goods [num=" + num + ", name=" + name + ", price=" + price + ", desp=" + desp + "]" ; } public void display() { System.out.println(num+ " " +name+ " " +price+ " " +desp); } } |
这是Constructor测试类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.winking.fanshe; import java.lang.reflect.Constructor; import org.junit.Test; public class ConstructorTest_GoodTest { @Test /** * 获得无参的构造方法 */ public void demo1() throws Exception{ Class class1 =Class.forName( "/jdbc/src/com/winking/fanshe/Goods.java" ); Constructor c =class1.getConstructor(); Goods goods =(Goods) c.newInstance(); goods.display(); } /** * 获得有参的构造方法 * @throws Exception */ public void demo2() throws Exception { Class class2=Class.forName( "/jdbc/src/com/winking/fanshe/Goods.java" ); Constructor c2=class2.getConstructor(Integer. class ,String. class ,Integer. class ,String. class ); Goods goods=(Goods) c2.newInstance( 1 , "电视机" , 25 , "我是是是" ); System.out.println(goods); } } |
运行的时候,没有反应,而且会有红色条:
5
收起
正在回答
2回答
同学你好,报错信息提示没有找到对应的构造方法,
同学可以如下修改一下:
因为构造方法中对应的的int
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
3. Java 数据库开发与实战应用
- 参与学习 人
- 提交作业 357 份
- 解答问题 8016 个
本阶段将带你学习MySQL数据库,JDBC接口,MyBatis框架等,带你掌握的数据的存放和管理。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧