" are parameterized types, such as "List" and "Map"."/> " are parameterized types, such as "List" and "Map".">

Home  >  Article  >  Java  >  How to use reflection to obtain generic information in java

How to use reflection to obtain generic information in java

王林
王林forward
2019-11-29 15:40:002494browse

How to use reflection to obtain generic information in java

ParameterizedType means parameterized type.

Explanation:

Anything with "" in the declared type is a parameterized type, such as List<integer></integer>, Map<string></string>.

getActualTypeArguments()Return Type[], which is the parameters in "", such as Map<string></string>.

getRawType() Return to Tpye and get the type in front of "", such as List<string></string>.

getOwnerType() Returns Type. When calling a variable of type O.I, O will be returned, such as Map.Entry<long> </long>.

Free teaching video sharing: java course

Example code:

import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Map;
public class ReflectDemo {
    private static Map<String, BigDecimal>map;
    @Test
    public void test(){
        try {
            Class<?> aClass = Class.forName("com.test.annotation.param.ReflectDemo");
            //获取map属性对象
            Field field = aClass.getDeclaredField("map");
            //获取map属性的类型
            Type type = field.getGenericType();//返回属性声明的Type类型
            if (type instanceof ParameterizedType) {
                //强转为ParameterizedType对象
                ParameterizedType parameterizedType = (ParameterizedType) type;
                //获取原始类型
                Type rawType = parameterizedType.getRawType();
                System.out.println("map的原始类型为:"+rawType);
                //获取map的类型的所有泛型信息
                Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                for(int i=0;i<actualTypeArguments.length;i++){
                    System.out.println("Map类型的第"+(i+1)+"个泛型为:"+actualTypeArguments[i]);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Running result:

How to use reflection to obtain generic information in java

Recommended java related articles and tutorials: java introductory tutorial

The above is the detailed content of How to use reflection to obtain generic information in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete