论坛首页 入门技术论坛

给群里的人写了个反射的小例子,扔这儿吧(超入门级,没吃过反射的进)

浏览 1552 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-12-18   最后修改:2008-12-26
如果忘记一个Object的type如何取出Field中的values
public class People {
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
}


import java.lang.reflect.Field;

public class Test {

	public static void main(String[] args) throws Exception {
		People beibei = new People();
		beibei.setName("beibei");
		beibei.setAge(23);
		Field[] fs = beibei.getClass().getDeclaredFields();
		for(Field f: fs){
			String methodName = "get"+upChar(f.getName());
			System.out.println(
					beibei.getClass().getMethod(methodName, null).invoke(beibei, null)
			);
		}
	}
	
	private static String upChar(String str){
		char[] str2 = str.toCharArray();
		if(str2[0]>='a'&&str2[0]<'z') {
			str2[0]=(char)(str2[0]-32); 
		} 
		return new String(str2);		
	}
}
   发表时间:2008-12-23  
...咋连个注释都没有哩
0 请登录后投票
   发表时间:2008-12-26  
yinsuxiaokucha 写道
...咋连个注释都没有哩


就这么几行可读性很差么?
你要是真的需要注释我可以加上
真的需要么?
0 请登录后投票
   发表时间:2008-12-26  
mayday85 写道
yinsuxiaokucha 写道
...咋连个注释都没有哩


就这么几行可读性很差么?
你要是真的需要注释我可以加上
真的需要么?

String methodName = "get"+upChar(f.getName()); 
这个自写方法写个注释更好.

PS:首字母?
StringUtils.capitalize
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics