练习
来源:2-6 自由编程
慕姐4139960
2021-02-06 22:33:59
TestGoods.java
package com.zoro.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestGoods {
public static void main(String[] args) {
try {
Class goodsClass = Class.forName("com.zoro.reflect.Goods");
Constructor constructor = goodsClass.getConstructor(new Class[]{
String.class, String.class, double.class, String.class
});
Goods goods2 = (Goods)constructor.newInstance(new Object[]{
"001", "mooc手机", 3999, "6.58英寸大屏, 超长待机"});
System.out.println(goods2);
String newDesc = "6.58英寸大屏,超长待机,超级快充,6400万高清四摄";
System.out.println("商品描述信息更改为:" + newDesc);
Method method = goodsClass.getMethod("display", String.class);
method.invoke(goods2, newDesc);
System.out.println(goods2);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
Goods.java
package com.zoro.reflect;
public class Goods {
private String num;
private String title;
private double price;
private String desc;
public Goods() {
}
public Goods(String num, String title, double price, String desc) {
this.setNum(num);
this.setTitle(title);
this.setPrice(price);
this.setDesc(desc);
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "Goods{" +
"num='" + num + '\'' +
", title='" + title + '\'' +
", price=" + price +
", desc='" + desc + '\'' +
'}';
}
public void display(String desc) {
this.setDesc(desc);
}
}
1回答
好帮手慕阿园
2021-02-07
同学你好,练习题完成的不错,继续加油呐
祝学习愉快~