课题打卡,请老师检查
来源:2-9 自由编程
慕前端8369922
2020-08-17 09:19:10
package practice3; public class Book { private int no; private String name; public Float price; public Book() { } @Override public String toString() { return "Book{" + "no=" + no + ", name='" + name + '\'' + ", price=" + price + '}'; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } 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(int no, String name, Float price) { this.no = no; this.name = name; this.price = price; } }
package practice3; 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("practice3.Book"); Constructor constructor = bookClass.getConstructor(int.class, String.class, Float.class); Book book = (Book) constructor.newInstance(1, "How to Sell an apple", 34f); Field[] fileds = bookClass.getDeclaredFields(); for( Field field: fileds){ if( field.getModifiers() == 1 ){ Object val = field.get(book); System.out.println(field.getName() + ": " + val); }else if(field.getModifiers() == 2 ){ String methodName = "get" + field.getName().substring(0,1).toUpperCase() + field.getName().substring(1); Method method = bookClass.getMethod(methodName); Object val = method.invoke(book); System.out.println(field.getName() + ": " + val); } } } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } }
谢谢老师检查了
1回答
好帮手慕小尤
2020-08-17
同学你好,同学的代码完成的不错哦,很棒,继续加油!
祝学习愉快!
相似问题