请老师检查
来源:2-6 自由编程
谁叫我这么坏
2020-11-29 10:50:36
package com.imooc.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
try {
Class goodsClass= Class.forName("com.imooc.reflect.Goods");
Constructor goodsConstructor=goodsClass.getConstructor(new Class[]{String.class, String.class, float.class, String.class});
Goods goods=(Goods)goodsConstructor.newInstance(new Object[]{"001", "mooc手机", 3999f, "6.58英寸大屏,超长待机"});
System.out.println(goods);
Method displayMethod=goodsClass.getMethod("display", String.class);
String newDesp = "6.58英寸大屏,超长待机,超级快充,6400万高清四摄";
displayMethod.invoke(goods,newDesp);
System.out.println(goods);
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
package com.imooc.reflect;
public class Goods {
private String id;
private String name;
private float price;
private String desp;
public Goods(){
}
public Goods(String id, String name, float price, String desp) {
this.id = id;
this.name = name;
this.price = price;
this.desp = desp;
}
public String getId() {
return id;
}
public void setId(String 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(String desp) {
this.setDesp(desp);
System.out.println(this.getName()+"商品描述更改为:"+desp);
}
}
1回答
已完成练习,棒棒哒!继续加油!
相似问题