Preface:
Recently, the company is undergoing a business componentization process, and the routing implementation uses Java's reflection mechanism. Since it is used, I want to study and summarize it carefully. In fact, whether it is the previous EventBus 2.x version, Retrofit, or early View annotation framework, it uses Java's reflection mechanism to a greater or lesser extent.
What is the Java reflection mechanism?
The JAVA reflection mechanism is that in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any method of its dynamically acquired and dynamically calling the object method is called Java reflection mechanism.
What functions does the reflection mechanism provide?
Java reflection mechanism class:
java.lang.Class; //Class java.lang.reflect.Constructor; //Constructor method java.lang.reflect.Field; //Class member variable java.lang.reflect.Method; //Class method java.lang.reflect.Modifier; //Access permissions
Java reflection mechanism implementation:
1.) Getting class object
//The first method is to use the object getClass method Person person = new Person();Class<?> class1 = person.getClass();//The second method is to use the class attribute class1 = Person.class;try { //The third method is to use the static method of the Class class - forName() to implement class1 = Class.forName("com.whoislcj.reflectdemo.Person");} catch (ClassNotFoundException e) { e.printStackTrace();}2.) Get the summary information of the class object
boolean isPrimitive = class1.isPrimitive();//Judge whether it is the basic type boolean isArray = class1.isArray();//Judge whether it is a collection class boolean isAnnotation = class1.isAnnotation();//Judge whether it is an annotation class boolean isInterface = class1.isInterface();//Judge whether it is an interface class boolean isEnum = class1.isEnum();//Judge whether it is an enum class boolean isAnonymousClass = class1.isAnonymousClass();//Judge whether it is an anonymous internal class boolean isAnnotationPresent = class1.isAnnotationPresent(Deprecated.class);//Judge whether it is modified by a certain annotated class String className = class1.getName();//Get class name contains the package name path Package aPackage = class1.getPackage();//Get class package information String simpleName = class1.getSimpleName();//Get class class name int modifiers = class1.getModifiers();//Get class access permissions Class<?>[] declaredClasses = class1.getDeclaredClasses();//Inner class Class<?> declareClass = class1.getDeclaringClass();//External class
3.) Get the attributes, methods, constructors, etc. of the class object
Field[] allFields = class1.getDeclaredFields();//Get all attributes of the class object Field[] publicFields = class1.getFields();//Get the public attribute of the class object try { Field ageField = class1.getDeclaredField("age");//Get the specified attribute of the class Field desField = class1.getField("des");//Get the specified public attribute of the class} catch (NoSuchFieldException e) { e.printStackTrace();}Method[] methods = class1.getDeclaredMethods();//Get all declaration methods of class object Method[] allMethods = class1.getMethods();//Get all methods of class object including the method of parent class Class parentClass = class1.getSuperclass();//Get the parent class of class object Class<?>[] interfaceClasses = class1.getInterfaces();//Get all interfaces of class object Constructor<?>[] allConstructors = class1.getDeclaredConstructors();//Get all declaration constructors of class object Constructor<?>[] publicConstructors = class1.getConstructors();//Get the class object public constructor try { Constructor<?> constructor = class1.getDeclaredConstructor(new Class[]{String.class});//Get the specified declaration constructor publicConstructor = class1.getConstructor(new Class[]{});//Get the specified declaration public constructor} catch (NoSuchMethodException e) { e.printStackTrace();}Annotation[] annotations = class1.getAnnotations();//Get all annotations of the class object Annotation annotation = class1.getAnnotation(Deprecated.class);//Get the specified annotation of the class object Type genericSuperclass = class1.getGenericSuperclass();//Get the TypeType[] interfaceTypes = class1.getGenericInterfaces();//Get the type collection of all interfaces of the class object 4.) Dynamic generation of class objects
//The first method of Class object calls the newInstance() method to generate Object obj = class1.newInstance();//The second method of the object obtains the corresponding Constructor object, and then generates the Constructor<?> constructor = class1.getDeclaredConstructor(new Class[]{String.class});//Get the specified declaration constructor obj = constructor.newInstance(new Object[]{"lcj"});5.) Dynamically call functions
try { // Generate a new object: use the newInstance() method Object obj = class1.newInstance(); //Judge whether the object is a subclass of Person boolean isInstanceOf = obj instanceof Person; //First of all, you need to obtain the method corresponding to this method Method method = class1.getDeclaredMethod("setAge", new Class[]{int.class}); //Call the specified function and pass the parameter method.invoke(obj, 28); method = class1.getDeclaredMethod("getAge"); Object result = method.invoke(obj, new Class[]{});} catch (InstantiationException e) { e.printStackTrace();} catch (IllegalAccessException e) { e.printStackTrace();} catch (NoSuchMethodException e) { e.printStackTrace();} catch (InvocationTargetException e) { e.printStackTrace();} 6.) Obtain generic types through reflection mechanism
For example, the following structure
//People class public class People<T> {}//Person class inherits People class public class Person<T> extends People<String> implements PersonInterface<Integer> {}//PersonInterface interface public interface PersonInterface<T> {}Get generic types
Person<String> person = new Person<>();//The first way is to use the object getClass method Class<?> class1 = person.getClass(); Type genericSuperclass = class1.getGenericSuperclass();//Get TypeType[] interfaceTypes = class1.getGenericInterfaces();//Get the Typeset of all interfaces of the class object getComponentType(genericSuperclass); getComponentType(interfaceTypes[0]);
getComponentType implementation
private Class<?> getComponentType(Type type) {Class<?> componentType = null;if (type instanceof ParameterizedType) { //getActualTypeArguments() returns an array of Type objects representing the actual type parameters of this type. Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments(); if (actualTypeArguments != null && actualTypeArguments.length > 0) { componentType = (Class<?>) actualTypeArguments[0]; }} else if (type instanceof GenericArrayType) { // Array type that represents an element type that is a parameterized type or type variable componentType = (Class<?>) ((GenericArrayType) type).getGenericComponentType();} else { componentType = (Class<?>) type;}return componentType;} 6.) Obtain annotation information through reflection mechanism
Here we focus on obtaining the annotation information of the Method as an example
try { //First of all, you need to obtain the method object corresponding to this method Method method = class1.getDeclaredMethod("jumpToGoodsDetail", new Class[]{String.class, String.class}); Annotation[] annotations1 = method.getAnnotations();//Get all method annotation information Annotation annotation1 = method.getAnnotation(RouterUri.class);//Get the specified annotation information TypeVariable[] typeVariables1 = method.getTypeParameters(); Annotation[][] parameterAnnotationsArray = method.getParameterAnnotations();//Get all parameter annotations information Class<?>[] parameterTypes = method.getParameterTypes();//Get all parameters class type Type[] genericParameterTypes = method.getGenericParameterTypes();//Get all parameters type type Class<?> returnType = method.getReturnType();//Get the return type of the method int modifiers = method.getModifiers();//Get the access permissions of the method} catch (NoSuchMethodException e) { e.printStackTrace();}Application scenarios of reflection mechanism:
Advantages and disadvantages of reflection mechanism:
Advantages: judgment of runtime type, dynamic class loading, and dynamic proxy use reflection.
Disadvantages: Performance is a problem. Reflection is equivalent to a series of explanation operations. Notifying jvm about what to do, performance is much slower than direct java code.
Summarize:
The reflection mechanism of Java is rarely used in daily business development, but it is widely used in the construction of some basic frameworks. Today I briefly summarized and learned it, and there are still a lot of unknown knowledge to be used later to supplement it.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.