Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ways to use the Java reflection type Type

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian for you to introduce in detail the "Java reflection type Type use methods", the content is detailed, the steps are clear, the details are handled properly, I hope that this "Java reflection type Type use method" article can help you solve doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge bar.

Each method 1. Get the member variables of class

First get the class object of object

Then use the getDeclaredFields () method in the class object to get the member variables of class

FieldTest ft = new FieldTest (); Class ftClass = ft.getClass (); Field [] fields = ftClass.getDeclaredFields (); 2.Function of field

Field objects have many member methods

GetName () gets the name.

GetGenericType () returns a Type object

GetType () returns a Class object

The difference between getGenericType and getType:

The return type is a Class object and a Type interface.

If the property is generic, getType () returns the interface type of the property. GetGenericType () can also return the parameter type.

String fieldName = field.getName (); Type genericType = field.getGenericType (); boolean isParameterizedType = (genericType instanceof ParameterizedType); Class fieldClazz = field.getType (); String valueTypeName = genericType.getTypeName (); 3. Get the Type and Class of the paradigm

Get the key of paradigm and the Type of value

Type [] genericTypes = ((ParameterizedType) genericType) .getActualTypeArguments (); Type type0 = genericTypes [0]; Type type1 = genericTypes [1]

Get the key of map or the class type of value through the com.google.common.reflect.TypeToken.of (type1) .getRawType () method of google.

Class clazz = com.google.common.reflect.TypeToken.of (type1). GetRawType (); total code class FieldTest {private String pri; protected String pro; public Map fcmap; public FieldTest () {} public FieldTest (String pri, String pro, String pub) {this.pri = pri; this.pro = pro;}} package cn.hyperchain.hvm.abi;import java.lang.reflect.Array;import java.lang.reflect.Field Import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.Arrays;import java.util.HashMap;import java.util.Map;public class Test {private static boolean checkClazzIsSpecific (Class CClazz, Class specific) {if (CClazz = = specific) return true; Class [] interfaces = CClazz.getInterfaces (); boolean result = false; for (Class inter: interfaces) {if (result) break If (inter = = specific) {result = true; break;} result = checkClazzIsSpecific (inter, specific);} return result;} public static void main (String args []) {FieldTest ft = new FieldTest (); Class ftClass = ft.getClass (); Field [] fields = ftClass.getDeclaredFields () For (int I = 0; I < fields.length; iTunes +) {Field field = fields [I]; String fieldName = field.getName (); Type genericType = field.getGenericType (); Class fieldClass = field.getClass (); boolean isParameterizedType = (genericType instanceof ParameterizedType); Class fieldClazz = field.getType (); String valueTypeName = genericType.getTypeName () System.out.println (); System.out.println ("- -"); System.out.println (); System.out.println ("fieldName:" + fieldName) System.out.println ("genericType:" + genericType); System.out.println ("fieldClazz:" + fieldClazz); System.out.println ("isParameterizedType:" + isParameterizedType); System.out.println ("valueTypeName:" + valueTypeName); if (checkClazzIsSpecific (fieldClazz, Map.class)) {Type [] genericTypes = ((ParameterizedType) genericType). GetActualTypeArguments () Type type0 = genericTypes [0]; Type type1 = genericTypes [1]; String type1Name = genericTypes [1] .getTypeName (); System.out.println ("type0:" + type0); System.out.println ("type1:" + type1); System.out.println ("type1Name:" + type1Name) System.out.println (type1 instanceof ParameterizedType); Type type3 = ((ParameterizedType) type1). GetOwnerType (); Class type4 = type1.getClass (); / / Class type5 = (Class) type1; System.out.println ("type3:" + type3); System.out.println ("type4:" + type4) / / System.out.println (type5); Class clazz = com.google.common.reflect.TypeToken.of (type1). GetRawType (); System.out.println ("clazz:" + clazz);} class FieldTest {private String pri; protected String pro;// public Map map; public Map fcmap Public FieldTest () {} public FieldTest (String pri, String pro, String pub) {this.pri = pri; this.pro = pro;}} class abc {private String pri; protected String pro; public String pub; public String [] string; public int [] innt; public Map map; public abc () {} public abc (String pri, String pro, String pub) {this.pri = pri This.pro = pro; this.pub = pub;}} result:

FieldName: pri

GenericType: class java.lang.String

FieldClazz: class java.lang.String

IsParameterizedType: false

ValueTypeName: java.lang.String

FieldName: pro

GenericType: class java.lang.String

FieldClazz: class java.lang.String

IsParameterizedType: false

ValueTypeName: java.lang.String

FieldName: fcmap

GenericType: java.util.Map

FieldClazz: interface java.util.Map

IsParameterizedType: true

ValueTypeName: java.util.Map

Type0: class java.lang.Integer

Type1: java.util.HashMap

Type1Name: java.util.HashMap

True

Type3: null

Type4: class sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl

Clazz: class java.util.HashMap

Process finished with exit code 0

Add: Java- uses reflection to get type information

How do I use reflection to get type information in Java?

Recently, I have written a lot of code that needs to reflect and inject values based on the type of class attributes, summing up the following common reflection techniques:

An example of a simple class

In this class, there are normal String types, array types, List types with generics, nested List types, and simple classes with multiple generic parameters, which will serve as the basis for the rest of our content. This time our blog parses how to use reflection to get the type values of different attributes.

Public class Some {private String name; private Integer [] numbers; private List list; private List matrix; private Map map; / / ignore getter and setter} analyzes how to get types 1 and common types of different attributes

Ordinary type variables can get their types directly by field.getType ().

Public void queryNameType () throws NoSuchFieldException {Field field = Some.class.getDeclaredField ("name"); Class type = field.getType (); assertEquals (type,String.class);} 2, array type

Unlike other types, array types can be determined by the isAssignableFrom () function. He needs to use isArray () to determine whether the type is an array type, and then use getComponentType () to get the type of his element.

Public void queryArrayType () throws NoSuchFieldException {Field field = Some.class.getDeclaredField ("numbers"); Class type = field.getType () / / generally speaking, you can use isAssignableFrom / / to determine whether an array type is a certain type. To use the function isArray (), if (type.isArray ()) {/ / to get the type of the array, use getComponentType () this method Class componentType = type.getComponentType (); assertEquals (componentType,Integer.class);} else {throw new IllegalStateException () 3. Types with generics

Types with generics are types like List, and our task now is to get the type String.

ParameterizedType represents parameterized types, such as Collection. We can get the subclass through the getGenericType () method, which will return ParameterizedType when your type has parameters, otherwise it will return the normal type (class)

So how does it operate exactly?

Take getting the type of List as an example

Public void getListType () throws NoSuchFieldException {Field field = Some.class.getDeclaredField ("list"); / / if a type like List is a GenericType / / Note that this is a Type type Type type = field.getGenericType (); if (type instanceof ParameterizedType) {/ / generic parameter type ParameterizedType parameterizedType = (ParameterizedType) type; Type [] actualTypes = parameterizedType.getActualTypeArguments () / / because List gets the first generic parameter, because there is only one, we take the first / / if we have multiple generic parameters, we can take different generic parameters assertEquals (actualTypes [0], String.class) according to the order; / / what if we get the original type List? AssertEquals (parameterizedType.getRawType (), List.class);} else {throw new IllegalStateException ();}} 4, complex nesting types

If it's List, how do you get the innermost type?

Examples are as follows

Public void getSubListType () throws NoSuchFieldException {/ / think about it, if we have a nested List and we want to get the innermost type, then we can do that? / in fact, we can use recursive thinking to get the innermost type Field field = Some.class.getDeclaredField ("matrix"); assertEquals (getBaseType (field.getGenericType ()), Double.class);} public static Type getBaseType (Type genericReturnType) {Objects.requireNonNull (genericReturnType); if (genericReturnType instanceof ParameterizedType & & List.class.isAssignableFrom (Class) ((ParameterizedType) genericReturnType). GetRawType ()) {Type [] actualTypeArguments = (ParameterizedType) genericReturnType). GetActualTypeArguments () Type type = actualTypeArguments [0]; return getBaseType (type);} else {return genericReturnType;}} 5, multiple generic parameters

Similar to the third example, you only need to use the actualTypes array to fetch it in order.

Examples are as follows

Public void getMapType () throws NoSuchFieldException {Field field = Some.class.getDeclaredField ("map"); Type type = field.getGenericType (); if (type instanceof ParameterizedType) {ParameterizedType parameterizedType = (ParameterizedType) type; Type [] actualTypes = parameterizedType.getActualTypeArguments (); assertEquals (actualTypes [0], String.class); assertEquals (actualTypes [1], Class.class);} else {throw new IllegalStateException () }} after reading this, the article "what is the use of Java reflection type Type" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report