Java by specifying the class object for the classes, the program can get all the field included in the class, regardless of whether the field uses private adornments or public adornments. Once the Field object is obtained, it is easy to get the data type of the field, for example, the following code is the type that gets the Field object Foeld:
class<?> type = Field.gettype ();
However, this method is only valid for a normal type of field, and if the field type is a type with a generic restriction, such as the map<string,integer> type, you cannot accurately get the generic parameter of the field.
In order to obtain a generic type for the specified field, you should use the following method to get the generic type for the specified field:
Type type = Field.getgenerictype ();
The type object is then coerced into the Parameterizedtype object, Parameterizedtype represents the parameterized type, which is the type that adds the generic limit, and the Parameterizedtype class provides two methods:
Getrawtype (); Returns the type that is restricted by the generic type;
Getactualtypearguments (); Returns the generic parameter type.
Below, let's take a look at a complete example to make it easy for you to master:
ImportJava.lang.reflect.Field;ImportJava.lang.reflect.ParameterizedType;ImportJava.lang.reflect.Type;ImportJava.util.HashMap;ImportJava.util.Map; Public classGenerictest {Privatemap<string, integer> map =NewHashmap<string, integer>(); Public Static voidMain (string[] args)throwsSecurityException, nosuchfieldexception {//Get class instanceclass<generictest> Class1 = generictest.class; //Gets the Field object corresponding to the attribute based on the property nameField Mapfield = Class1.getdeclaredfield ("Map"); //demonstration of the first method: The Type of field is removed directly from the GetType (), only valid for normal type fieldclass<?> Class2 =Mapfield.gettype (); //Output ViewSystem.out.println ("attribute type with attribute name map is:" +Class2); //demonstration of the second method:Type Mapmaintype =Mapfield.getgenerictype (); //to ensure safe conversion, use instanceof if(MapmaintypeinstanceofParameterizedtype) { //perform a forced type conversionParameterizedtype Parameterizedtype =(Parameterizedtype) Mapmaintype; //gets the basic type information, which is the mapType Basictype =Parameterizedtype.getrawtype (); System.out.println ("Base type:" +Basictype); //get generic parameters for generic typestype[] Types =parameterizedtype.getactualtypearguments (); for(inti = 0; i < types.length; i++) {System.out.println ("First" + (i + 1) + "generic type is:" +Types[i]); } } Else{System.out.println ("Getting generic type Error!"); } }}
Reference: http://blog.csdn.net/ieayoio/article/details/46395667
Java uses reflection to get member variable generic information