Gets the generic type defined on the interface or class

Source: Internet
Author: User

The type of the parent class or interface is obtained by Getgenericsuperclass () or getgenericinterfaces () on class. Then through Parameterizedtype.getactualtypearguments ()

You can get a generic type defined on a class or interface, as in the following code:

 Packagecom.jiaoyiping.event;/** Created with Intellij idea * USER: Coke A flat * Mail: [email protected] * DATE:2016/12/4 * time:9:28 * to change t His template use File | Settings | Editor | File and Code Templates*/ImportJava.lang.reflect.ParameterizedType;ImportJava.lang.reflect.Type; Public classGenerictypetest {Static classTest1extendsT<person, animal> {    }    Static classTest2ImplementsI<person, Animal>, i2<fruit> {    }     Public Static voidMain (string[] args) {//gets the generic type on the class definitionTest1 test1 =NewTest1 (); Type Types=Test1.getclass (). Getgenericsuperclass (); Type[] GenericType=((Parameterizedtype) types). Getactualtypearguments ();  for(Type t:generictype) {System.out.println (T.gettypename ()); } System.out.println ("==============================================="); //gets the generic type on the interface definitionTest2 test2 =NewTest2 (); //A class may implement multiple interfaces, and the generic types defined on each interface are preferable totype[] Interfacestypes =Test2.getclass (). Getgenericinterfaces ();  for(Type t:interfacestypes) {type[] genericType2=( (Parameterizedtype) t). Getactualtypearguments ();  for(Type t2:generictype2) {System.out.println (T2.gettypename ()); }        }    }}classT&LT;T1, t2> {     Public voidPrintt (T1 t1, T2 T2) {System.out.println (T1.getclass ());    System.out.println (T2.getclass ()); }}InterfaceI&LT;T1, t2> {}InterfaceI2<k> {}classPerson {@Override PublicString toString () {return"Person Type"; }}classAnimal {@Override PublicString toString () {return"Animal Type"; }}classFruit {@Override PublicString toString () {return"Fruit Type"; }}

Gets the generic type defined on the interface or class

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.