Parent class is a subclass of a generic class that inherits the parent class

Source: Internet
Author: User
Implementation: The parent class is a generic class, the subclass inherits the parent class,
This allows the generic object to be obtained in the parent class. is the generic type that is set when the subclass inherits the parent class.




If, for example, it is under a COM package
The parent class is: public class person<t>
Subclass: public class Student extends person<student>


Getsuperclass () Gets the parent class of the class: Com. Person
Getgenericsuperclass () Gets the parent class (if there is generics, also bring the generics): COM. Person<com. Student>


Getgenericsuperclass () If the parent class is not a class with a generic type. The result returned is the same as Getsuperclass ().


Gets the generic parameter type.


This.getclass (). Getgenericsuperclass () Gets the parent class (if there is a generic, gets the parent class with the generic type)


((Parameterizedtype) This.getclass (). Getgenericsuperclass ()). Getactualtypearguments () [0] Gets the first parameter type of a generic parameter




Getactualtypearguments () The method is to get a generic type array, [0] to get the first value




===================== Example: ======================
Parent class:
public class Dao<t> {

Private class<t> entity;


/**
*
*/
Public Dao () {
Super ();
TODO auto-generated Constructor stub
System.out.println ("Class:" +this.getclass ());
Entity= (class<t>) ((Parameterizedtype) This.getclass (). Getgenericsuperclass ()). Getactualtypearguments () [0] ;
System.out.println (Entity.getname ());
}

Public class<t> getentity () {
return entity;
}
}


Sub-class:
public class Userdao extends dao<user>{


public void Test1 () {
System.out.println ("Name:" +this.getentity (). GetName ());
}
}


JavaBean
public class User {


String name;
String ID;
}


Test:
public class Testmain {


public static void Main (string[] args) {
Userdao dao=new Userdao ();
Dao.test1 ();
}
}
===================== Example: ======================

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.