日期:2014-05-20  浏览次数:21056 次

如何获取一个类里面的所有参数,及参数值?

我有一个JAVA类,里面有private String参数若干, 是用get,set来存取它们的. 

现在我想输出一个字符串 ,格式是 : "参数1=xxx|参数2=xxx2|参数3=xxx3|..."

大概用什么函数,? 能否给个提示.

------解决方案--------------------
用Reflection

import java.lang.reflect.*;
public class DumpMethods {
public static void main(String args[]) {
try {
Class c = Class.forName(args[0]);
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString());
} catch (Throwable e) {
System.err.println(e);
}
}
}


------解决方案--------------------
/**
* toString
* @return String
*/
public String toString(){
StringBuffer buff = new StringBuffer();
Method[] m = this.getClass().getMethods();
final int idx = 3;
try {
for(int i=0;i <m.length;i++) {
String methodName = m[i].getName();
if (methodName.startsWith( "get ") && !methodName.endsWith( "Class ")) {
String className = m[i].getReturnType().getName();
Object o = m[i].invoke(this, new Object[]{});
if (o != null) {
buff.append(methodName.substring(idx)).append( "=[ ").append(o).append( "] ");
}
}
}
}catch(IllegalAccessException iae) {
iae.printStackTrace();
}catch(InvocationTargetException ite) {
ite.printStackTrace();
}
return buff.toString();
}