Skip to content

Instantly share code, notes, and snippets.

@GeekaholicLin
Created October 24, 2016 13:59
Show Gist options
  • Save GeekaholicLin/1c59e28ae022093d1cb1a19302f7b737 to your computer and use it in GitHub Desktop.
Save GeekaholicLin/1c59e28ae022093d1cb1a19302f7b737 to your computer and use it in GitHub Desktop.
Java动态设置属性值

从文件中读取数据,然后利用反射在运行时更新属性的值。

在初次看到这个作业的时候,我的做法是,分割字符串(字符串中,每一行为fieldName = fieldValue的形式), 然后将字符串使用parseInt()等类似的方法转换为int 类型和boolean类型的属性值。

 String[] filedAndValue = filedValue.split("[=\\n]");//分割字符串,前面为属性名,后面为属性值
        int fHalfLength = (filedAndValue.length) / 2;
        for (int i = 0; i < fHalfLength; i++) {
            Field f = personClass.getDeclaredField(filedAndValue[2 * i].trim());
            f.setAccessible(true);
            Object value = null;
            //System.out.println(f.getType().toGenericString());
            if (f.getType().toGenericString().equals("int")) {
                value = Integer.parseInt(filedAndValue[2 * i + 1].trim());
            } else if (f.getType().toGenericString().equals("boolean")) {
                value = Boolean.parseBoolean(filedAndValue[2 * i + 1].trim());
            } else value = filedAndValue[2 * i + 1].trim();
            f.set(newPerson, value);//field 对象的set方法
            newFiledVaule += f.getName() + " = " + f.get(newPerson) + "\n";
        }

而教材的答案中则是利用了各个属性值对应的set方法。

private void analyzeFile(String text){
		String[] values=text.split("=");
		String methodName="set"+StringUtil.firstCharToUpper(values[0]);//拼接成set**方法名
		setAttr(methodName.trim(),values[1].trim());//调用下面的setAttr()函数
	}
	
	private void setAttr(String methodName,Object value){
		try {
			Method[] method=clazz.getDeclaredMethods();
			for(Method m:method){
				if(m.getName().equals(methodName)){//若为属性对应的set方法
					Class[] paramType=m.getParameterTypes();
					String type=paramType[0].getCanonicalName();//获取参数的类型
					m.invoke(person,Class.forName(type).getConstructor(String.class).newInstance(value));
          //最重要的一句代码:Class.forName(type).getConstructor(String.class).newInstance(value)
          //Class.forName(type)---拿到class对象
          //Class.forName(type).getConstructor(String.class)
          //---获取该类型(比如int)的参数为String类型的构造函数【因为读取的数据都是String】
          //Class.forName(type).getConstructor(String.class).newInstance(value) --使用构造函数"强制"转换为该类型(int)的值
					return;
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment