有时我们需要在调试过程中显示bean的当前数据,利用reflect可以快速的对大量的bean对象进行统一的处理,下面的代码就实现了将数据提出的公共方法。当然也可以使用其它开源库,但是为什么我们自己不了解一下呢!
public void ShowFileds(Object obj)
{
System.out.println("Target class is "+ obj.getClass().getName());
try{
String ClassName = obj.getClass().getName();
Class cls = Class.forName(ClassName);
Method[] methods = cls.getDeclaredMethods();
for(int i =0; i< methods.length; i++)
{
Method method = methods[i];
String mName = method.getName();
if(mName.substring(0, 3).equals("get"))
{
System.out.println(mName.substring(3, mName.length())+ " : " + method.invoke(obj, null));
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
以上方法没有针对特定的Bean,而是自动解析任何符合要求的Bean对象,并对其进行域显示!