请老师看一下

来源:3-7 自由编程

96年的nash

2019-05-16 11:46:55

package com.hxh.reflect.practise;

public class Book {
    private Integer book_id;
    private String book_name;
    public Double book_price;

    public Book() {
    }

    public Book(Integer book_id, String book_name, Double book_price) {
        this.book_id = book_id;
        this.book_name = book_name;
        this.book_price = book_price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "book_id=" + book_id +
                ", book_name='" + book_name + '\'' +
                ", book_price=" + book_price +
                '}';
    }
}
package com.hxh.reflect.practise;
import java.lang.reflect.Field;

import org.junit.Test;

public class FieldTest {
	
	@Test
	public void fieldTest1() throws Exception {
		Class class1 = Class.forName("com.hxh.reflect.practise.Book");
		Book book = (Book) class1.newInstance();
		
		//1、通过Field获得图书名称属性,设置新值并输出
		Field book_name = class1.getDeclaredField("book_name");
		book_name.setAccessible(true);
		book_name.set(book, "罗杰疑案");
		System.out.println(book);
		
		//2、通过Field获得图书价格,设置新值并输出
		Field book_price = class1.getField("book_price");
		book_price.set(book, Double.parseDouble("24"));
		System.out.println(book);
	}
	
}


写回答

1回答

吃吃吃鱼的猫

2019-05-16

同学你好,写的很棒~

继续加油吧~

为了老师能够跟踪,高效解决同学的问题,建议同学同一个问题不要创建多个问答哦~

祝:学习愉快~


0

0 学习 · 8016 问题

查看课程