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

How to use reflection to obtain generic information in java

王林
Release: 2019-11-29 15:40:00
forward
2594 people have browsed it

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();
        }
    }
}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template