标签:
public class R{ public static String TOKEN="default-value"; public static String APPID; ... }
TOKEN=SDLKFJL APPID=DFSLF ...
/** * 初始化变量,通过读取properties文件 */ public static void init(){ System. out.println( "开始初始化"); try { //1读取配置文件 Class c=R. class; // InputStream in = Class.forName("com.wupl.constant.R").getResourceAsStream("src/R.properties"); InputStream in = new BufferedInputStream( new FileInputStream("src/R.properties" )); Properties properties = new Properties(); properties.load(in); //通过反射获取所有string类型成员变量信息,并以此读取配置文件中的值并赋值。 Field [] fields = c.getDeclaredFields(); for( int i=0;i<fields. length;i++){ Field field = fields[i]; String fieldName=field.getName(); //判断是否是字符串类型,配置文件中有对应的key=value键值 if(field.getGenericType().toString().equals( "class java.lang.String")&& properties.containsKey( fieldName)){ String value=properties.getProperty(fieldName); //取值 System. out.println( "取到" +fieldName+ "--的值--" +value); field.set( fieldName, value); } } System. out.println( "初始化完毕" ); } catch (Exception e) { System. out.println( "初始化失败" ); e.printStackTrace(); } }
标签:
原文地址:http://blog.csdn.net/wplin007/article/details/51354354