Do you have any idea how to get a generic type parameter? In fact, this function in hibernate has a wide range of applications, then the specific operation is how?
First of all, it is obviously impossible to get the actual parameters of a generic type directly through a variable, refer to Hibernate source code, as long as the variable as a method parameter, and then through reflection can get the actual parameters of the generic type.
Public classgenericstest {@Test Public void Test7(){Try{//list<book> List = new arraylist<book> (); //Join now I want to get the actual type parameter in the list generic above, then write a method first as a parameter //Use reflection to get the actual type parameter of listMethod m = GenericsTest.class.getMethod ("Test8", List.class);//Get generic type parameterstype[] types = M.getgenericparametertypes ();//Because there is only one parameter, so we'll take the first one.Parameterizedtype pt = (parameterizedtype) types[0];//Get original typeSystem. out. println (Pt.getrawtype ());///Get the actual parameter type, the actual parameter type is also an array, such as Map<string,string> //There is only one parameter, we do not traverse theSystem. out. println (Pt.getactualtypearguments () [0]); }Catch(Nosuchmethodexception | SecurityException e) {e.printstacktrace (); } } Public void Test8(list<book> List) { }}
Book.java
Package lenve.test; Public classBook {Private intIdPrivateString name;Private intPricePrivateString author;PrivateDetail Detail;PrivateAttribute Attribute; PublicAttributegetattribute() {returnAttribute } Public void SetAttribute(Attribute Attribute) { This. Attribute = attribute; } PublicDetailGetdetail() {returnDetail } Public void Setdetail(Detail Detail) { This. detail = detail; } Public int getId() {returnId } Public void setId(intID) { This. id = ID; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int GetPrice() {returnPrice } Public void Setprice(intPrice) { This. Price = Price; } PublicStringGetauthor() {returnAuthor } Public void Setauthor(String author) { This. Author = author; } Public Book(string name, string author) { This. name = name; This. Author = author; } Public Book() { }}
Output:
What do you think? Get the actual type parameters!
Get the actual type parameters of a generic by reflection