Abdennour TOUMI
Abdennour TOUMI

Reputation: 93511

Getting Item_$$_javassist_165 from ins.getClass().getSimpleName()

I've three classes that implement the composite patter, Item, Cluster and Element.

class Item extends Locatable {
  ...
}

class Cluster extends Item {

    static hasMany = [items:Item]

  ...
}

class Element extends Item {
  ...
}

My domain model is more complex than this, but it's just an example. When I have an instance of Item and I want to know if it is a Cluster or a Element with ins.getClass().getSimpleName() I'm getting a weird class name: Item_$$_javassist_165, if I do a println ins.toString() I get the correct class name printed (the toString method returns this.getClass().getSimpleName()).

how to get the correct class name? What is this "Item_$$_javassist_165" class name?

Upvotes: 1

Views: 644

Answers (3)

micha
micha

Reputation: 49612

You can use GrailsHibernateUtil.unwrapIfProxy(object) to receive the original object instance from a proxy object. After unwrapping you should be able to get the real class name with getClass().getSimpleName(). Be aware that you loose features like lazy loading on the unwrapped object.

Upvotes: 2

Ian Roberts
Ian Roberts

Reputation: 122414

What is this "Item_$$_javassist_165" class name?

It means that the object you have is a Hibernate lazy-loading proxy. The first time you try and access anything other than the id of that object, Hibernate will go to the database and load the real data, then delegate any future method calls to the real object.

The obvious approach of ins instanceof Cluster may not work correctly in the presence of proxies when you have one domain class that extends another, but GORM provides an injected instanceOf method that does what you need and will handle proxies correctly.

if(ins.instanceOf(Cluster)) { .... }

Upvotes: 5

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93511

I find a method that give the real name:

org.hibernate.Hibernate.getClass(ins).getSimpleName()

Upvotes: 0

Related Questions