JAVA反射3-4自由编程

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

运行的时候,没有反应,而且会有红色条:

http://img1.sycdn.imooc.com//climg/5d47d55f00015fb019041018.jpg

正在回答

登陆购买课程后可参与讨论,去登陆

2回答

同学你好,报错信息提示没有找到对应的构造方法,

http://img1.sycdn.imooc.com//climg/5d47ea750001442613770332.jpg

同学可以如下修改一下:

http://img1.sycdn.imooc.com//climg/5d47ea2b00015bb008240147.jpg

因为构造方法中对应的的int

http://img1.sycdn.imooc.com//climg/5d47ea4b00017af106970080.jpg

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

好帮手慕阿莹 2019-08-05 16:04:57

同学你好,同学的Class.forName 中应该是(“com.winking.fanshe.Goods”)

http://img1.sycdn.imooc.com//climg/5d47e2e20001900007700266.jpg

下边的demo2同理呦。

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!


  • 提问者 qq_慕UI0173712 #1
    按照你修改后,demo1成功运行,但是demo2仍然出现问题。
    2019-08-05 16:31:52
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师
插入代码