在Java类中,我们可以使用反射中的getDeclaredFields()或者getFields()方法来获取属性和值。
比如测试类:
public class Test {
public int id;
public String name;
获取类的属性和值
public class Application {
public static void main(String[] args) throws Exception {
Test test = new Test();
test.id = 1;
test.name = "guoke";
// 遍历输出属性
Field[] fields = test.getClass().getDeclaredFields();
for( int i = 0; i < fields.length; i++){
Field f = fields[i];
System.out.println("属性名:"+f.getName()+",属性值:"+f.get(test));
设置类的属性值,比如做一个类成员属性深拷贝
public class Test {
public int id;
public String name;
public void copy(Test obj){
try {
Field[] fields = obj.getClass().getDeclaredFields();
for( int i = 0; i < fields.length; i++){
Field f = fields[i];
f.set(this, f.get(obj));
} catch (Exception e) {
Log.error(e);
public class Application {
public static void main(String[] args) throws Exception {
Test test = new Test();
test.id = 1;
test.name = "guoke";