Java Reflection (ix): generics

Source: Internet
Author: User

Reprinted from Concurrent Programming network –ifeve.com

Content index
The rule of thumb for using generic reflection
Generic method return type
Generic method parameter types
Generic variable type

I often read in some articles and forums that Java generic information is erased at compile time (erased) so you cannot get information about generics at run time. In fact, this statement is not entirely correct, in some cases it is possible to obtain generic information during the run-time. These situations actually cover some of the requirements that we need for generic information. In this section we will show you these cases.

The rule of thumb for using generic reflection

Here are two typical scenarios that use generics:
1. Declare a class/interface that needs to be parameterized (parameterizable).
2. Use a parameterized class.

When you declare a class or an interface, you can indicate that the class or interface can be parameterized, and the Java.util.List interface is a typical example. You can use a generic mechanism to create a list of string types labeled storage, which is better than creating a list of object.

When you want to parameterize the type itself at run time, for example if you want to check the parameterized type of the Java.util.List class, you have no way of knowing what his specific parameterized type is. This type can be all of the types in an application. However, when you examine a variable or method that uses a parameterized type, you can obtain the specific parameter of the parameterized type. Anyway:

You cannot know what the specific parameter type of a parameterized type is at run time, but you can find them in the methods and variables of the parameterized type, in other words, to learn their specific parameterized type.
In the following paragraphs, you will be shown this type of situation.

Generic method return type

If you get the Java.lang.reflect.Method object, you can get the generic return type information for this method. If the method is in a parameterized type (translator Note: such as T Fun ()) then you cannot get his specific type, but if the method returns a generic class (translator Note: such as List fun ()) then you can get the specific parameterized type of this generic class. You can read about how to get the method object in Java reflection:methods. The following example defines a class in which a method return type is a generic type:

 Public class MyClass {  protected list<string> stringlist = ...;    Public List<string> getstringlist () {    returnthis. stringlist;  }}

We can get the generic return type of the Getstringlist () method, in other words, we can detect that the Getstringlist () method returns a list instead of just a list. The following example:

 method = MyClass. class . GetMethod ("Getstringlist", null  ); Type returntype  = Method.getgenericreturntype ();  if     (ReturnType instanceof   Parameterizedtype) {    Parameterizedtype type  = (Parameterizedtype) ReturnType;    Type[] typearguments  = type.getactualtypearguments ();         for   (Type typeargument:typearguments) {        Class Typeargclass  = (Class) typeargument;    System.out.println ( typeargclass = "+ Typeargclass); }}

This code prints out "Typeargclass = java.lang.String", type[] array typearguments has only one result – an instance of the class class that represents Java.lang.String. class implements the type interface.

Generic method parameter types

You can also get the generic type of a method parameter by reflection, the following example defines a class in which the parameter of a method in this class is a parameterized list:

 Public class MyClass {  protected list<string> stringlist = ...;    Public void setstringlist (list<string> list) {    this. stringlist = list;  }} 

You can get the generic parameters of the method like this:

method = Myclass.class. GetMethod ("Setstringlist", List.class); Type[] Genericparametertypes=method.getgenericparametertypes (); for(Type genericparametertype:genericparametertypes) {if(GenericparametertypeinstanceofParameterizedtype) {Parameterizedtype Atype=(Parameterizedtype) Genericparametertype; Type[] Parameterargtypes=atype.getactualtypearguments ();  for(Type parameterargtype:parameterargtypes) {Class Parameterargclass=(Class) Parameterargtype; System.out.println ("Parameterargclass =" +Parameterargclass); }    }}

This code will print out "Parameterargtype = java.lang.String". Type[] Array parameterargtypes has only one result – an instance of the class class that represents Java.lang.String. class implements the type interface.

Generic variable type

You can also access the generic type of a public variable by reflection, whether that variable is a static member variable of a class or an instance member variable. You can read about how to get the Field object in Java reflection:fields. This is an example of a class that defines a member variable named Stringlist.

 Public classMyClass { PublicList<string> stringlist = ...;} Field field= MyClass.class. GetField ("Stringlist"); Type Genericfieldtype=Field.getgenerictype ();if(GenericfieldtypeinstanceofParameterizedtype) {Parameterizedtype Atype=(Parameterizedtype) Genericfieldtype; Type[] Fieldargtypes=atype.getactualtypearguments ();  for(Type fieldargtype:fieldargtypes) {Class Fieldargclass=(Class) Fieldargtype; System.out.println ("Fieldargclass =" +Fieldargclass); }}

This code will print out "Fieldargclass = java.lang.String". Type[] Array Fieldargclass has only one result – an instance of the class class that represents Java.lang.String. class implements the type interface.

Original address Author: Jakob Jenkov Translator: Yevenhai ([email protected])

Java Reflection (ix): 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.