作者Chikei ( )
看板AndroidDev
標題Re: [問題] 如何做到給一個string轉成變數或涵式名稱
時間Wed Apr 27 18:11:01 2011
Reflect.java
import java.lang.reflect.Field;
import java.util.Arrays;
import static java.lang.System.out;
public class Reflect {
public int test = 5;
public static void main(String... args)
{
Reflect reflect = new Reflect();
try
{
Class<?> clazz = reflect.getClass();
Field test = clazz.getDeclaredField("test");
int reflectTest = test.getInt(reflect);
out.println(reflectTest);
test.setInt(reflect, 6);
out.println(reflect.test);
} catch (NoSuchFieldException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
執行結果
chikei@gentoo ~ $ java Reflect
5
6
這樣不行?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 211.72.92.133
1F:→ ericinttu:有些地方看不懂 XD 先推 04/27 18:52
2F:→ hateexam:大感謝^^ 04/28 01:20