Here's how I solved the problem of excluding Fields that are JPA/Hibernate
entities from the ReflectionToStringBuilder:
public String toString() {
class MyReflectionToStringBuilder extends ReflectionToStringBuilder
{
private MyReflectionToStringBuilder(Object object, ToStringStyle
style) {
super(object, style);
this.setAppendTransients(false);
}
/**
* Overloading of method accept() to exclude fields that are
instances of Entities,
* and as such LazyInit exception prone.
*
* Check if the given field has an @Entity annotation.
* The above should be enough in the future, but in the mean
time,
* we check also the name of the field's super class in case
it's not already annotated with JPA @Entity
*/
@SuppressWarnings({"SimplifiableIfStatement"})
public boolean accept(Field field) {
if (field.getType().isAnnotationPresent(Entity.class))
return false;
Type superclass = field.getType().getGenericSuperclass();
if (superclass != null &&
!superclass.toString().contains("ModelObject"))
return false;
return super.accept(field);
}
}
;
ReflectionToStringBuilder tsb = new
MyReflectionToStringBuilder(this, MyToStringStyle.getInstance());
return tsb.toString();
}
The . isAnnotationPresent() method is very convenient in case you can
identify your classes with an Annotation, otherwise, I use
getType().getGenericSuperclass().toString() to check the superclass name.
nodje wrote:
>
> Hi,
>
> I'm using ReflectionToStringBuilder to build a default toString() for all
> my Hibernate entities.
> It creates problem with non initialized Fields when outside of an open
> session.
>
> Basically, I'd like to be able to exclude all entity subobjects by putting
> them in ExcludeFieldNames so that they don't get accessed.
>
> I can't see any way to do that with the actual implementation. Do you
> think it's possible at all with the actual 2.4 implementation? What about
> 2.5.
>
> If not, I'll certainly have to implement my own ReflectionToStringBuilder
> with the ability of exluding fields that are <? extends ModelObject>. I
> wish I woudn't have to use 'instanceof' but I can't see any other way.
>
> thanks for your help.
>
--
View this message in context:
http://www.nabble.com/-Lang--excluding-Fields-in-ReflectionToStringBuilder-tp23886050p24267251.html
Sent from the Commons - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]