课题打卡~请老师检查

来源:2-9 自由编程

慕仙4530950

2020-07-29 16:24:39

public class getDeclaredBook {
    public static void main(String[] args) {
        try {
            Class bookClass = Class.forName("com.imooc.reflect.entity.Book");
            Constructor constructor = bookClass.getConstructor(new Class[]{
                    Integer.class, String.class, Float.class
            });
            Book book = (Book) constructor.newInstance(new Object[]{
                    1001, "计算机编程语言", 89f
            });
            Field[] fields = bookClass.getDeclaredFields();
            for (Field field : fields) {
                //System.out.println(field.getName());
                if (field.getModifiers() == 1) { //public修饰
                    Object val = field.get(book);
                    System.out.println(field.getName() + ":" + val);
                } else if (field.getModifiers() == 2) { //private修饰
                    String methodName = "get" + field.getName().substring(0, 1).toUpperCase()
                            + field.getName().substring(1);
                    Method method = bookClass.getMethod(methodName);
                    Object ret = method.invoke(book);
                    System.out.println(field.getName() + ":" + ret);
                }
            }
        } 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();
        }
    }
}
public class Book {
    private Integer bookId;
    private String bookName;
    public Float price;

    public Book(){

    }

    public Book(Integer bookId, String bookName, Float price) {
        this.bookId = bookId;
        this.bookName = bookName;
        this.price = price;
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookId=" + bookId +
                ", bookName='" + bookName + '\'' +
                ", price=" + price +
                '}';
    }
}


写回答

1回答

好帮手慕小脸

2020-07-29

同学你好,同学的代码完成的不错哦,很棒,继续加油!!

如果我的回答解决了你的问题,请采纳,祝学习愉快.


0

0 学习 · 16556 问题

查看课程