Basic class:
@Repositorypublic class hibernatedao<t, PK extends serializable>{ protected Logger Logger = Loggerfactory.getlogger (GetClass ()); protected class<t> Entityclass; Public Hibernatedao () { logger.debug (string.valueof (Getentityclass ())); } /** * For generic class type * @return * /protected class<t> Getentityclass () { Logger.debug (" This.class: "+ this.getclass ()); Logger.debug ("This.getclass (). Getgenericsuperclass ():" + This.getclass (). Getgenericsuperclass ()); if (null = = Entityclass) { Entityclass = (class<t>) ((Parameterizedtype) This.getclass (). Getgenericsuperclass ()). Getactualtypearguments () [0]; } Logger.debug ("Entityclass:" + entityclass); return entityclass; } ....}
@Repositorypublic class basedao<t, PK extends serializable> extends hibernatedao<t,string> {}
The application layer handles the specific business @repositorypublic class Userdao extends Basedao<user, string> {}
The inheritance relationship is obvious, and I'm now instantiating Basedao in Basesrvice:
@Service @transactionalpublic abstract class baseservice<t, PK extends serializable> { protected Logger Logger = Loggerfactory.getlogger (This.getclass ()); @Autowired private Basedao Basedao; Public Baseservice () { printentityclass (); } Helps to understand private void Printentityclass () { Parameterizedtype type = (Parameterizedtype) this.getclass (). Getgenericsuperclass (); Class C = (Class) type.getactualtypearguments () [0]; Logger.debug (C.tostring ()); } ...}
I then wrote a test class in JUnit, "Note: Test instances of the application tier":
public class Userservicetest extends Basetestconfig { @Autowired private userservice userservice; @Test public void TestList2 () { String id = "40283a814f7d92f7014f7d956bf50007"; Userservice.get (ID);} }
Run results
Explain that Hibernatedao when seeking generics, throw an exception.
Modify the next Baseservice to
@Autowiredprivate Basedao Basedao;
Switch
@Autowiredprivate basedao<t,string> Basedao;
Run again:
Exception disappears, note: Hibernatedao changes in the print output of the generic type.
II.this.getClass (). Getgenericsuperclass (); Find the direct parent class. such as Userdao's direct parent class is Basedao instead of Hibernatedao.
Multiple inheritance to find the type of a generic class