Gets the actual type of the generic (generic class) parameter type T (actual type)

Source: Internet
Author: User

If you want to get the generic (generic class) parameter type T, you might use the following code:

Class<t> Tclass = (class<t>) ((Parameterizedtype) GetClass (). Getgenericsuperclass ())
. Getactualtypearguments () [0];

Gets the actual generic parameter type of the immediate base class of the current class (you are new);
However, you may encounter the following two exceptions:

1.java.lang.classcastexception:libcore.reflect.typevariableimpl 
cannot is cast to Java.lang.Class
2. Java.lang.ClassCastException:java.lang.Class 
cannot be cast to Java.lang.reflect.ParameterizedType

The new object is not a generic, and converting to Parameterizedtype will throw an exception 2, Getactualtypearguments (), to get the actual incoming type, then the actual type T needs to be passed to this class;
If you want to get the actual type, you should do this: the anonymous inner class of the new generic class, as follows:

    Class Atest<t> {public
        atest () {
            class<t> T = (class<t>) (Parameterizedtype) GetClass (). Getgenericsuperclass ())
            . getactualtypearguments () [0];
            LOG.I ("T is:" + t);
        }
    

Call new Atest<string> () {};
Result: T Is:class java.lang.String
If {} is omitted, the direct base class of atest is the object

The following code:

    Class Atest<t> {public
        atest () {
            log.i ("atest");
        }

    Class Btest<t> extends Atest<t> {public
        btest () {
. getactualtypearguments () [0];
            LOG.I ("T is:" + t);
        }
New Btest<string> ();

So called Getgenericsuperclass () gets the atest, which is the Parameterizedtype type, but because the actual type passed in the Btest,atest parameter is T, not the actual type, will report an exception 1
The correct approach is new btest<string> () {};

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.