" are parameterized types, such as "List Home >Java >javaTutorial >How to use reflection to obtain generic information in java Explanation: Anything with "" in the declared type is a parameterized type, such as Free teaching video sharing: java course Example code: Running result: 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!How to use reflection to obtain generic information in java
ParameterizedType
means parameterized type. 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, OMap.Entry<long> </long>
. 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();
}
}
}