Bootstrap

java反射设置属性值_Java反射:根据属性名得到其Set方法设置它的值

设置

A a = new A();

Field field = a.getClass().getDeclaredField("x");

field.setAccessible(true);

field.set(a, 1);

读取

Field f = a.getClass().getDeclaredField("x");

f.setAccessible(true);

System.out.println(f.get(a));

import java.lang.reflect.Field;

public class A {

private String x = "0";

public static void main(String[] ag) {

A a = new A();

Field field = null;

try

{

field = a.getClass().getDeclaredField("x");

try

{

System.out.println("xiugaiqiandezhi-----------------"

+ field.get(a));

}

catch (IllegalArgumentException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (IllegalAccessException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

catch (SecurityException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (NoSuchFieldException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

field.setAccessible(true);

try

{

field.set((Object) a, "1");

}

catch (IllegalArgumentException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (IllegalAccessException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

// 读取

Field f = null;

try

{

f = a.getClass().getDeclaredField("x");

}

catch (SecurityException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (NoSuchFieldException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

f.setAccessible(true);

try

{

System.out.println("xiugaihoudezhi-----------------" + f.get(a));

}

catch (IllegalArgumentException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (IllegalAccessException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

输出

xiugaiqiandezhi-----------------0

xiugaihoudezhi-----------------1

;