3-7 编程题

来源:3-7 自由编程

JakePrim

2020-02-24 23:15:41

private static void testBook(){
    try {
        Class clz = Class.forName("com.prim.reflection.Book");
        Object instance = clz.newInstance();
        Field nameField = clz.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(instance,"Java编程思想");
        System.out.println(nameField.get(instance));

        Field priceField = clz.getField("price");
        priceField.set(instance,84.5f);
        System.out.println(priceField.get(instance));


    }catch (Exception e){
        e.printStackTrace();
    }
}
package com.prim.reflection;

public class Book {
    private String id;
    private String name;
    public float 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 +
                '}';
    }
}


写回答

1回答

好帮手慕小班

2020-02-25

同学完成的不错,加油,祝学习愉快~

0

0 学习 · 8016 问题

查看课程

相似问题