反照获取对象成员的字段值,getFields()和getDeclaredFields()用法区别

反射获取对象成员的字段值,getFields()和getDeclaredFields()用法区别
  用反射获取内部类的属性其实很简单。。我弄了半天才弄好,由于很弱智的原因啊,写此博文已吸取教训。
  虽简单,但是太坑爹了,getFields()只能获取public的字段,包括父类的。
  而getDeclaredFields()只能获取自己声明的各种字段,包括public,protected,private。
  而我写的Characters类中的属性是在继承父类的,父类中是protected的,所以获取不到,这个弄了我半天!最后只要把父类的protected属性全改成public的就ok了啊。。

  还有getFields()和getDeclaredFields(),返回的都是Field对象,获取名称直接field.getName(),但是属性值则是field.get(Object),这个object是该field所属的!!!

  太坑爹了,绕了好多弯啊!!!不过这样却对反射获得字段有了深刻的理解。
  具体代码如下:
/**
	 * 生成java实体类的核心方法
	 * @param clazz
	 * @param targetDir
	 */
	public void genFile(Class<?> clazz, String targetDir) {
		String className = clazz.getSimpleName();
		// 获取模板
		Template temp = null;
		try {
			temp = cfg.getTemplate("testEntity.ftl");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// 返回所有字段成员(id, account, name, profession...)
		Field[] enums = clazz.getDeclaredFields();
		// 遍历每个枚举成员, 获取属性, 放入Map中
		Map<String, Object> targetClazz = new HashMap<String, Object>();
		Map<String, Map<String, String>> fields = new HashMap<String, Map<String, String>>();
		targetClazz.put("className", className);
		targetClazz.put("fields", fields);
		for (Field e : enums) {
			Map<String, String> field = new HashMap<String, String>();
			String name = e.getName();
			try {
				Object obj = e.get(clazz);
				Class<?> type = (Class<?>) obj.getClass().getField("type").get(obj);
				field.put("name", name);
				field.put("type", type.getSimpleName());
			} catch (SecurityException e1) {
				e1.printStackTrace();
			} catch (NoSuchFieldException e1) {
				e1.printStackTrace();
			} catch (IllegalArgumentException e1) {
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			}
			fields.put(e.toString() + "field", field);
		}
		
		/* 将模板和数据合并,并生成文件 */
		File dir = new File(targetDir);
		if(!dir.exists())	dir.mkdirs();
		File target = new File(targetDir + className + "Entity.java");
		Writer out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(target));
			temp.process(targetClazz, out);
			out.flush();
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}


还有其父类部分代码改过之后是:
public abstract class EntityConfCommon {
	public Class<?> type;
	public int length;
	public String index;
	public String defaults;
	public boolean isNull;

main方法是:
	public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InstantiationException {
		Class<Character> c = Character.class;

		FreemarkerGenEntity generator = new FreemarkerGenEntity();
		generator.init();
		generator.genFile(c, "d:\\test\\");
		
	}

这样就没问题了!