求助:用反射机制来得到简单bean的所有的值, 也就是代替toString()方法. 如题. 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 一个简单的javabean里边有一些private 的属性还有get(), set() 方法。怎么用反射来代替toString()方法呢。ps:公司要求记日志用,有一个input参数要求记录输入条件。可是javabean都没有toString()方法。 可以试试以下代码。它会给你一个类的所有的读方法:import java.beans.PropertyDescriptor;import java.lang.reflect.Method;import org.apache.commons.beanutils.PropertyUtils;import com.java.test.utils.Person;public class PropertyDescriptorDriver { public static void main(String[] args) { PropertyDescriptor[] descs = PropertyUtils.getPropertyDescriptors(Person.class); for(PropertyDescriptor desc : descs){ Method method = desc.getReadMethod(); } }} 没太看懂楼主的要求但是可以通过反射取得所有get方法,在invork应该就可以了。不过反射new出来的对象,对于所有的域来说都是null,楼主可以再想想办法。package reflect;public class SampleBean{ private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}package reflect;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class SampleReflect{ public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { reflect(); } public static void reflect() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { try { Class cls = Class.forName("reflect.SampleBean"); Constructor<SampleBean> con = cls.getConstructor(); SampleBean bean = (SampleBean)con.newInstance(); for(Field field: cls.getDeclaredFields()) { System.out.println(field.toString()); } for(Method method : cls.getDeclaredMethods()) { if(method.getName().contains("get")) { System.out.println(method.invoke(bean, new Object[]{})); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } }} BeanInfoPrinter.javapackage reflect;import java.lang.reflect.Method;import java.util.Collection;import java.util.Iterator;import java.util.Map;public class BeanInfoPrinter { public static void printBeanInfo(Object obj) { Method[] mths = obj.getClass().getMethods(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < mths.length; i++) { try { if (!"getClass".equals(mths[i].getName()) && (mths[i].getName().startsWith("get") || mths[i] .getName().startsWith("is"))) { Object result = mths[i].invoke(obj, new Class[] {}); if (result instanceof Collection) { buf.append(result.getClass().getName()); buf.append("["); Collection c = (Collection) result; Iterator iterator = c.iterator(); while (iterator.hasNext()) { buf.append(iterator.hasNext()).append(","); } buf.append("]"); } else if (result instanceof Map) { buf.append(result.getClass().getName()); buf.append("["); Map m = (Map) result; Iterator iterator = m.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.hasNext(); buf.append(key).append(":").append(m.get(key)).append(","); } buf.append("]"); } else { buf.append(result); } buf.append(","); } } catch (Exception e) { e.printStackTrace(); } } System.out.println(buf.toString()); } public static void main(String[] args) { DemoBean db = new DemoBean(); printBeanInfo(db); }}DemoBean.javapackage reflect;import java.util.ArrayList;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;public class DemoBean { private int i = 0; private double d = 0d; private float f = 0f; private long l = 0l; private String str = ""; private List list = new ArrayList(); private Map map = new HashMap(); private Set set = new HashSet(); public double getD() { return d; } public void setD(double d) { this.d = d; } public float getF() { return f; } public void setF(float f) { this.f = f; } public int getI() { return i; } public void setI(int i) { this.i = i; } public long getL() { return l; } public void setL(long l) { this.l = l; } public List getList() { return list; } public void setList(List list) { this.list = list; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public Set getSet() { return set; } public void setSet(Set set) { this.set = set; } public String getStr() { return str; } public void setStr(String str) { this.str = str; }} 请教4楼,这个题目的应用场景是什么呢,像我们这样通过反射得到一个bean,那么这个bean中各个域的值谁来给赋呢?或者是在什么时机赋值呢?望解答,多谢~~ 关键不在于赋值而在于你的bean对象能否得到能得到,你就可以用我给出的方法,直接打印,或者略略修改后改为输出到log4j或者slf4j。XXX obj = xxxxxx;BeanInfoPrinter.printBeanInfo(obj); 恩 很好啊 多谢 。就是在打印出来的时候没有打印 属性名。我期望是这样的firstName:jim;secondName:Green;age:12;感谢3位啊,结贴。 如何理解Runtime这个类运行时 关于object的hashcode 谁能帮我分析一下java_this? 时间轮转的问题.恳请指点!!!!!!!! 有关java文件输入输入的一道题,知道的帮我解决一下 关于servlet,请帮忙!! 新人请教一个简单的Reflection问题 哪位高手帮忙编一下 有一个GUI的问题~~~~~解决就给分~~~~~ 在linux下怎么配置java虚拟机,jdk之类的东西啊? javac.exe、 java.exe、 java虚拟机三者之间的区别与联系? 初学者请教
里边有一些private 的属性
还有get(), set() 方法。
怎么用反射来代替toString()方法呢。ps:公司要求记日志用,有一个input参数要求记录输入条件。可是javabean都没有toString()方法。
import java.lang.reflect.Method;import org.apache.commons.beanutils.PropertyUtils;import com.java.test.utils.Person;public class PropertyDescriptorDriver { public static void main(String[] args) {
PropertyDescriptor[] descs = PropertyUtils.getPropertyDescriptors(Person.class);
for(PropertyDescriptor desc : descs){
Method method = desc.getReadMethod();
}
}
}
但是可以通过反射取得所有get方法,在invork应该就可以了。
不过反射new出来的对象,对于所有的域来说都是null,楼主可以再想想办法。package reflect;
public class SampleBean
{
private String id;
private String name; public String getId()
{
return id;
} public void setId(String id)
{
this.id = id;
} public String getName()
{
return name;
} public void setName(String name)
{
this.name = name;
}}
package reflect;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class SampleReflect
{ public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException
{
reflect();
}
public static void reflect() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException
{
try
{
Class cls = Class.forName("reflect.SampleBean");
Constructor<SampleBean> con = cls.getConstructor();
SampleBean bean = (SampleBean)con.newInstance();
for(Field field: cls.getDeclaredFields())
{
System.out.println(field.toString());
}
for(Method method : cls.getDeclaredMethods())
{
if(method.getName().contains("get"))
{
System.out.println(method.invoke(bean, new Object[]{}));
}
}
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
package reflect;import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;public class BeanInfoPrinter {
public static void printBeanInfo(Object obj) {
Method[] mths = obj.getClass().getMethods();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < mths.length; i++) {
try {
if (!"getClass".equals(mths[i].getName())
&& (mths[i].getName().startsWith("get") || mths[i]
.getName().startsWith("is"))) {
Object result = mths[i].invoke(obj, new Class[] {});
if (result instanceof Collection) {
buf.append(result.getClass().getName());
buf.append("[");
Collection c = (Collection) result;
Iterator iterator = c.iterator();
while (iterator.hasNext()) {
buf.append(iterator.hasNext()).append(",");
}
buf.append("]");
} else if (result instanceof Map) {
buf.append(result.getClass().getName());
buf.append("[");
Map m = (Map) result;
Iterator iterator = m.keySet().iterator();
while (iterator.hasNext()) {
Object key = iterator.hasNext();
buf.append(key).append(":").append(m.get(key)).append(",");
}
buf.append("]");
} else {
buf.append(result);
}
buf.append(",");
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(buf.toString());
} public static void main(String[] args) {
DemoBean db = new DemoBean();
printBeanInfo(db);
}
}DemoBean.java
package reflect;import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;public class DemoBean {
private int i = 0; private double d = 0d; private float f = 0f; private long l = 0l; private String str = ""; private List list = new ArrayList(); private Map map = new HashMap(); private Set set = new HashSet(); public double getD() {
return d;
} public void setD(double d) {
this.d = d;
} public float getF() {
return f;
} public void setF(float f) {
this.f = f;
} public int getI() {
return i;
} public void setI(int i) {
this.i = i;
} public long getL() {
return l;
} public void setL(long l) {
this.l = l;
} public List getList() {
return list;
} public void setList(List list) {
this.list = list;
} public Map getMap() {
return map;
} public void setMap(Map map) {
this.map = map;
} public Set getSet() {
return set;
} public void setSet(Set set) {
this.set = set;
} public String getStr() {
return str;
} public void setStr(String str) {
this.str = str;
}
}
望解答,多谢~~
而在于你的bean对象能否得到
能得到,你就可以用我给出的方法,直接打印,或者略略修改后改为输出到log4j或者slf4j。
XXX obj = xxxxxx;
BeanInfoPrinter.printBeanInfo(obj);
就是在打印出来的时候没有打印 属性名。
我期望是这样的
firstName:jim;secondName:Green;age:12;感谢3位啊,结贴。