Java 如何通过反射获取对象中的场?
我在Java中有一个对象(基本上是VO),我不知道它的类型。Java 如何通过反射获取对象中的场?,java,reflection,Java,Reflection,我在Java中有一个对象(基本上是VO),我不知道它的类型。 我需要获取该对象中不为null的值 如何做到这一点?您可以使用获取类的所有声明字段。您可以使用来获取值 简言之: Object someObject = getItSomehow(); for (Field field : someObject.getClass().getDeclaredFields()) { field.setAccessible(true); // You might want to set modifi
我需要获取该对象中不为null的值 如何做到这一点?您可以使用获取类的所有声明字段。您可以使用来获取值 简言之:
Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
field.setAccessible(true); // You might want to set modifier to public first.
Object value = field.get(someObject);
if (value != null) {
System.out.println(field.getName() + "=" + value);
}
}
要了解有关反射的更多信息,请查看
这就是说,字段不一定全部表示VO的属性。您更希望确定以
get
或is
开头的公共方法,然后调用它来获取不动产值
for (Method method : someObject.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& (method.getName().startsWith("get") || method.getName().startsWith("is"))
) {
Object value = method.invoke(someObject);
if (value != null) {
System.out.println(method.getName() + "=" + value);
}
}
}
反过来说,可能有更优雅的方法来解决你的实际问题。如果您对您认为这是正确的解决方案的功能需求进行了详细阐述,那么我们可能会建议正确的解决方案。有很多很多工具可用于处理javabeans 我有一个对象(基本上是一个VO) Java,我不知道它的类型。我需要获取该对象中不为null的值 也许你不需要反思——这里有一个简单的OO设计可以解决你的问题:
Validation
,该接口公开一个方法validate
,该方法检查字段并返回任何适当的内容李>
Validation
,并轻松地进行检查我想您需要null字段以通用方式显示错误消息,所以这就足够了。如果出于某种原因,这对您不起作用,请告诉我。这里有一个快速而肮脏的方法,它以一种通用的方式实现了您想要的功能。您需要添加异常处理,并且可能希望在weakhashmap中缓存BeanInfo类型
public Map<String, Object> getNonNullProperties(final Object thingy) {
final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
try {
final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
.getClass());
for (final PropertyDescriptor descriptor : beanInfo
.getPropertyDescriptors()) {
try {
final Object propertyValue = descriptor.getReadMethod()
.invoke(thingy);
if (propertyValue != null) {
nonNullProperties.put(descriptor.getName(),
propertyValue);
}
} catch (final IllegalArgumentException e) {
// handle this please
} catch (final IllegalAccessException e) {
// and this also
} catch (final InvocationTargetException e) {
// and this, too
}
}
} catch (final IntrospectionException e) {
// do something sensible here
}
return nonNullProperties;
}
公共映射getNonNullProperties(最终对象){
final Map nonNullProperties=new TreeMap();
试一试{
final BeanInfo BeanInfo=Introspector.getBeanInfo(thingy
.getClass());
对于(最终属性描述符描述符:beanInfo
.getPropertyDescriptors()){
试一试{
最终对象propertyValue=descriptor.getReadMethod()
.调用(某物);
if(propertyValue!=null){
nonNullProperties.put(descriptor.getName(),
财产价值);
}
}捕获(最终非法辩论例外e){
//请处理这个
}捕获(最终非法访问例外e){
//这也
}捕获(最终调用TargetException e){
//还有这个
}
}
}捕获(最终内省异常e){
//在这里做些明智的事情
}
返回非空属性;
}
请参阅以下参考资料:
- (JavaDoc)
- (JavaDoc)
- (新加坡) 教程)