利用反射获取Java类中的静态变量名及变量值的简单实例
程序员文章站
2024-03-08 19:43:18
java可以通过反射获取成员变量和静态变量的名称,局部变量就不太可能拿到了。
public class test {
public static voi...
java可以通过反射获取成员变量和静态变量的名称,局部变量就不太可能拿到了。
public class test { public static void main(string[] args) throws exception { // todo auto-generated method stub //获取所有变量的值 class clazz = class.forname("com.qianmingxs.scoretable"); field[] fields = clazz.getfields(); for( field field : fields ){ system.out.println( field.getname() + " " +field.getint(clazz) ); } //获取单个变量的值 /*class clazz = class.forname("com.qianmingxs.scoretable"); field field = clazz.getfield("five"); system.out.println( field.getint(clazz));*/ } }
其中要查看的java类是:
public class scoretable { private scoretable() {} public final static int five = 100;//成5 public final static int double_alive_four = 99;//双活4(分析对手用) public final static int alive_four_and_dead_four = 98;//活4死4(对手分析用) public final static int alive_four_and_alive_three = 96;//活4活3(分析对手用) public final static int alive_four_and_dead_three = 95;//活4死3(分析对手用) public final static int alive_four_and_alive_two = 94;//活4活2 public final static int alive_four = 93;//活4 public final static int double_dead_four = 92;//双死4 public final static int dead_four_and_alive_three = 91;//死4活3 public final static int dead_four_and_alive_two = 90;//死4活2 public final static int double_alive_three = 80;//双活3 public final static int alive_three_and_dead_three = 70;//活死3 public final static int half_alive_four = 65;//半活4(类似○○ ○形),优先级小于活4 public final static int alive_three = 60;//活3 public final static int dead_four = 50;//死4 public final static int double_alive_two = 40;//双活2 public final static int dead_three = 30;//死3 public final static int alive_two = 20;//活2 public final static int dead_two = 10;//死2 public final static int single = 0;//单个 }
以上这篇利用反射获取java类中的静态变量名及变量值的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。