例1:
java.util.Calendar clndr = java.util.Calendar.getInstance();
Class cls = clndr.getClass();
System.out.println(cls.getName());
java.lang.reflect.Field[] flds = cls.getFields();
if ( flds != null )
{
for ( int i = 0; i < flds.length; i++ )
{
System.out.println(flds.getName() + " - " + flds.get(clndr));
}
}
//元组.get(对象),得到该元组所对应的对象属性的属性值。
例2:
java利用反射技术遍历某个对象的属性及属性值
package com.bean;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Test3 {
public static void main(String[] args) {
TestBean tb=new TestBean();
tb.setA("2012-8-5");
tb.setB("bbb");
tb.setC("ccc");
try {
Map<String,String> map=readClassAttr(tb);
System.out.println(map.get("keys"));
System.out.println(map.get("values"));
} catch (Exception e) {
e.printStackTrace();
}
}
//用来遍历对象属性和属性值
public static Map<String,String> readClassAttr(TestBean tb) throws Exception{
Field[] fields=tb.getClass().getDeclaredFields();
String keyList="";
String valueList="";
for(Field field:fields){
field.setAccessible(true);
if(field.get(tb)!=null&&!"".equals(field.get(tb).toString())){
keyList+=","+field.getName();
if("a".equals(field.getName())){
valueList+=","+"特殊格式哦";
}else{
valueList+=","+field.get(tb);
}
///System.out.println(field.getName()+" "+field.get(tb).toString());
}
}
Map<String,String> maps=new HashMap<String, String>();
maps.put("keys", keyList);
maps.put("values",valueList);
return maps;
}
例3:转自:
http://zhidao.baidu.com/question/202202923.html
遍历对象内部成员,在反射里面有方法,我刚练习完,只有将对象的成员分解到数组中才行。分享给你了:
Class c=Class.forName("AbstractClassTest.Car"); //要包名+类名
Object o=c.newInstance();
Car car=(Car)o;
Field[] fields=c.getDeclaredFields();//拿到数据成员
Method[] methods=c.getMethods();//拿到函数成员
/*System.out.println(fields.length);
System.out.println(methods.length);*/
for(Field f : fields){
System.out.println("该类的内部变量有:"+f.getName());
}
for(Method m : methods) {
System.out.println("该类的方法有:"+m.getName());