0

I'm using spring and cglib and i have those classes:

public class A {
   .
   .
   private Souscripteur souscripteur;

   private List<B> contrat;

   // getter and setter
}

public class B {
   .
   .
   private Souscripteur souscripteur;

//getter and setter
}

and the Class A and B have the same souscripteur, so when i load the Class A and try to load the class B, i get the Souscripteur of the class B EnhancerByCGLIB.

For that, when i try to do this :

if(b.getSouscriteur() instanceof PersonnePhysique) {
//do something
} else {
//do nothing
}

when i inspect the code, the object enhanced is a PersonnePhysique, but if(b.getSouscriteur() instanceof PersonnePhysique) return false

My class PersonnePhysique is like this :

public class PersonnePhysique extends Souscriteur {
//
}
Sidaoui Majdi
  • 399
  • 7
  • 26

1 Answers1

0

Hibernate generates proxies based on the declared, expected type (Souscripteur), so you'll get a lazy-loaded proxy extending Souscripteur - hence, no PersonnePhysique in the instanceof sense.

You have to avoid testing concrete types here, and rather call polymorphic methods on your entities (which is, by the way, more object-oriented).

Your use case, provided you are calling a method doSomething(), would become:

b.getSouscriteur().doSomething()

with the following implementations:

public class Souscripteur {
    public void doSomething() {
        // do nothing
    }
}

public class PersonnePhysique extends Souscripteur {
    @Override
    public void doSomething() {
        // do something here
    }
}
Vincent
  • 1,035
  • 6
  • 14