Java Key Technologies (24) using reflection to access parameterized types of generics

Source: Internet
Author: User

1.1. accessing parameterized types with reflection

Use the reflection mechanism to get information about a subset of parameterized types.

 Public classGENERICPARAMETERTEST5 {Static  classbase{}Static classGeneric<textendsBase>{  PublicT Work (list<t>list) {returnList.get (0);}  Publict work (t obj) {returnobj;}}  Public Static voidMain (string[] args) {Try {  //Public T-work (list<t> List) {Method method1= Generic.class. GetMethod ("Work", List.class); System.out.println (Method1.getparameters () [0].gettype ()); Type T1= Method1.getgenericparametertypes () [0]; Parameterizedtype PT=(parameterizedtype) T1; System.out.println ("Rawtype:" +Pt.getrawtype ()+ "Actualtype:" + pt.getactualtypearguments () [0].gettypename ()); System.out.println ("-------------"); //Public T-work (T obj) {Method method2= Generic.class. GetMethod ("Work", Base.class); System.out.println (Method2.getparameters () [0].gettype ()); Type T2= Method2.getgenericparametertypes () [0]; Typevariable<?> TV =(typevariable) T2; System.out.println (Tv.gettypename ()); Genericdeclaration GD=tv.getgenericdeclaration (); System.out.println (Gd.gettypeparameters () [0]); } Catch(Nosuchmethodexception |SecurityException e) {e.printstacktrace (); }}}

The results of the operation are as follows:

Interface Java.util.List

Rawtype:interface Java.util.listactualtype:t

-------------

Class Com.test.javatechnology.genericparameter.genericparametertest5$base

T

T

Java Key Technologies (24) using reflection to access parameterized types of generics

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.