用reflect包,3种方法 Class cls = java.awt.Point.class;
// By obtaining a list of all declared fields.
Field[] fields = cls.getDeclaredFields();
// By obtaining a list of all public fields, both declared and inherited.
fields = cls.getFields();
for (int i=0; i<fields.length; i++) {
Class type = fields[i].getType();
process(fields[i]);
}
// By obtaining a particular Field object.
// This example retrieves java.awt.Point.x.
try {
Field field = cls.getField("x");
process(field);
} catch (NoSuchFieldException e) {
}
// By obtaining a list of all declared fields.
Field[] fields = cls.getDeclaredFields();
// By obtaining a list of all public fields, both declared and inherited.
fields = cls.getFields();
for (int i=0; i<fields.length; i++) {
Class type = fields[i].getType();
process(fields[i]);
}
// By obtaining a particular Field object.
// This example retrieves java.awt.Point.x.
try {
Field field = cls.getField("x");
process(field);
} catch (NoSuchFieldException e) {
}
Class 有很多相应的方法如:
Field[] getDeclaredFields()
Method[] getDeclaredMethods()
Package getPackage()
然后java.lang.reflect包有相关的方法
如Method :
Object invoke(Object obj, Object[] args)
Class getReturnType()
Class[] getParameterTypes() ...............
即楼上很多兄弟所说的"就是用反射技术" !
org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors(bean);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
//name is bean property name
if ("class".equals(name)) {
continue; // No point in trying to set an object's class
}
if (org.apache.commons.beanutils.PropertyUtils.isReadable(orig, name) &&
org.apache.commons.beanutils.PropertyUtils.isWriteable(dest, name)) {
try {
Object value =
org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(orig, name);
//value is bean property value
} catch (NoSuchMethodException e) {
; // Should not happen
}
}
}
java要学的真是太多了