课题打卡-请老师检查
来源:2-9 自由编程
慕神0457710
2020-09-13 02:43:49
public class Book {
private String id;
private String name;
public float price;
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 Book() {
}
public Book(String id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
try {
Class bookClass = Class.forName("Book");
Constructor con = bookClass.getConstructor(new Class[]{String.class,String.class,float.class});
Book book = (Book)con.newInstance(new Object[]{"s001","天线宝宝",100f});
Field[] fields = bookClass.getDeclaredFields();
for (Field fie : fields) {
if (fie.getModifiers() == 1) {
Object var = fie.get(book);
System.out.println(fie.getName()+":"+var);
} else if((fie.getModifiers() == 2)) {
String methodName = "get"+fie.getName().substring(0,1).toUpperCase()+fie.getName().substring(1);
System.out.println(fie.getName()+":"+bookClass.getMethod(methodName).invoke(book));
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}1回答
同学你好,同学的代码完成的不错哦,很棒,继续加油!!
继续加油 祝学习愉快~
相似问题