What is reflection?

Reflection is one of the features of Java. It allows running Java programs to obtain information about themselves and manipulate the internal properties of classes or objects. In short, Reflection allows us to obtain information about the members and members of each type of program or assembly at run time. The typical object type in a program is determined at compile time, whereas Java reflection can dynamically create objects and call their properties, and the type of such objects is unknown at compile time. So we can use reflection to create objects directly, even if the type of the object is unknown at compile time. The core of reflection is that the JVM dynamically loads classes or invokes methods/accesses properties at run time, and it doesn’t need to know who the running object is beforehand (at code writing or compile time). Java reflection provides the following functions:

  • Determine the class of any object at run time;
  • Construct an object of any class at runtime;
  • Determine which member variables and methods any class has at run time (you can even call private methods through reflection);
  • The point of calling any object at run time: run time, not compile time

Use of reflection

Get the Class object

  • Class ClassforNameA static method
public static Class<? >forName(String className)
Copy the code
  • Gets the class of an object directly
Class<? > klass = int.class; Class<? > classInt = Integer.TYPE;Copy the code
  • Calling an objectgetClass()methods
StringBuilder str = new StringBuilder("123"); Class<? > klass = str.getClass();Copy the code

Determines whether it is an instance of a class

In general, we use the instanceof keyword to determine if it is an instanceof a class. At the same time, we can also use the isInstance() method of the Class object in reflection to determine whether it is an instance of a Class, which is a native method:

public native boolean isInstance(Object obj);
Copy the code

Create an instance

There are two main ways to generate objects through reflection.

  • Use the Class object’s newInstance() method to create instances of the corresponding Class of the Class object.
Class<? > c = String.class; Object str = c.newInstance();Copy the code
  • The Constructor object is obtained from the Class object and the newInstance() method of the Constructor object is called to create the instance. This method constructs an instance of a class with the specified constructor.
Class<? > c = String.class; Constructor = c.getconstructor (string.class); // Getconstructor = c.getconstructor (string.class); // Create instance Object obj = constructor.newinstance ("23333");
System.out.println(obj);
Copy the code

Gets constructor information

Method to get the constructor

Constructor getConstructor(Class[] params) -- get a public Constructor that uses a particular parameter type, Constructor[] getConstructors() -- getDeclaredConstructor(Class[] params) -- Constructor[] getDeclaredConstructors() -- Get all constructors of the class (regardless of the access level)Copy the code

The use of the class constructor is similar to the use of the method above. The Constructor Class has a newInstance method that creates an instance of an object:

public T newInstance(Object ... initargs)
Copy the code

Gets information about a class’s member variables (fields)

A method to obtain field information

Field getField(String name) -- get the named public Field Field[] getFields() -- get all public fields of the class Field getDeclaredField(String name) -- Get the named Field of the class declaration Field[] getDeclaredFields() - Get all fields of the class declarationCopy the code

A method is called

Methods for obtaining method information

Method getMethod(String name, Class[] params) -- uses a specific parameter type, Method getDeclaredMethod(String name, Class[] params) getDeclaredMethod(String name, Class[] params) Method[] getDeclaredMethods() - Get all methods of a class declarationCopy the code

When we get a method from a class, we invoke the method with the invoke() method. The invoke method prototype is:

public Object invoke(Object obj, Object... args)
        throws IllegalAccessException, IllegalArgumentException,
           InvocationTargetException
Copy the code

Create arrays using reflection

Arrays are a special type in Java that can be assigned to an Object Reference containing an Array class called java.lang.Reflect.array. We create an Array object with array.newinstance (), which looks like this:

public static Object newInstance(Class<? > componentType, int length) throws NegativeArraySizeException {return newArray(componentType, length);
    }
Copy the code

The newArray method is a native method, and its implementation in HotSpot JVM will be studied later. Here is the source code posted:

private static native Object newArray(Class<? > componentType, int length) throws NegativeArraySizeException;Copy the code

Matters needing attention

  • Reflection consumes additional system resources, so if you don’t need to create an object dynamically, you don’t need to use reflection
  • Reflection can ignore permission checks when calling methods, which can break encapsulation and cause security problems

The last

Thank you for your support. In the future, we will keep updating more selected dry goods and information sharing. Welcome to leave a message in the comment section to discuss!

Welcome to pay attention to enjoy learning class online wechat public number, every day will continue to update technology dry goods, hot, fun and other articles, as well as freeAndroidStructure video materials and interview special materials for free to receive and share, background reply keywords [Android information], free accessAndroidDocuments, ebooks and more advanced architecture videos (video + notes)