3-7 自由编程
package com.imooc.reflect.test;
import java.lang.reflect.Field;
import org.junit.Test;
public class FieldTest {
@Test
public void demo() throws Exception {
Class class1 = Class.forName("com.imooc.reflect.test.Book");
Field field = class1.getField("id");
Book book = (Book)class1.newInstance();
field.set(book, 1);
Object obj=field.get(book);
System.out.println(obj);
}
@Test
public void demo2() throws Exception {
Class class1 = Class.forName("com.imooc.reflect.test.Book");
Field field = class1.getDeclaredField("name");
Book book = (Book)class1.newInstance();
field.setAccessible(true);
field.set(book, "十万个为什么");
Object obj = field.get(book);
System.out.println(obj);
}
}
package com.imooc.reflect.test;
public class Book {
public int id;
private String name;
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + "]";
}
}
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 357 份
- 解答问题 8016 个
本阶段将带你学习MySQL数据库,JDBC接口,MyBatis框架等,带你掌握的数据的存放和管理。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星