Java Basics (b) reflection

reflection

Reflection mechanism provides the following functions:

  • In the run-time analysis class.

  • View objects at run time.

  • To achieve a common operation code array.

  • Use Methodobjects.

Due to the higher authority of reflection, when the use of its view run-time errors, but also pay attention to whether the break encapsulation procedures.

Class class

In fact, Classresponsible for information preservation class, not the object. Virtual machine type information to select the appropriate method for runtime execution.

In Objectclass getClassmethod returns an Classinstance of a type. Therefore, you can make a call to an object getClassmethod to obtain information about the object belongs. One of the most common class name can getNamebe obtained method, where the bags are also included in the class name.

// 假设e是某个类的实例
System.out.println(e.getClass().getName());

Conversely, by forNameobtaining method corresponding to the class name Classexamples.

// 这里要获取Random的Class实例,注意包名
Class cl = Class.forName("java.util.Random");
// 如果输入的类名不存在,会抛出“已检查异常”ClassNotFoundException。

There is a very simple way to get the Classclass object, that is, directly or type in Java voidafter adding keywords .class, get class object matching.

Class cl_1 = java.util.Random.class;
Class cl_2 = int.class;
Class cl_3 = Double[].class;

It is to obtain the above Classthree methods class object.

Gets Classthe class object, you can call the newInstancemethod to call the class default constructor , create an instance of the class. Here the requirements of this class must have a default constructor, otherwise it will throw an exception. If you want to use a constructor parameter containing, we should call Constructorclass newInstancemethod.

Analysis of the ability to reflect the use of the class

In java.lang.reflectclasses in a package Field, Methodand Constructorfields, methods and constructors for the class description. ModifierClass provides staticmethods and constants, can decode class and member access modifiers.

In Classclass getXXXmethod and getDeclaredXXXis quite different method returns an array of objects: The former returns the public and super class (superclass if any) , which returns all (excluding the superclass) .

NOTE: Constructorand Methodclass getParameterTypesmethods can return type constructor parameter or method Classobject array. MethodClass getReturnTypemethod returns the method's return type of the parameter Classobject.

In ModifierThere are a number of classes static booleana method for detection method modifier. getModifiersMethod returns the modifier intbit pattern memory , each represents a modifier. ModifierClass also provides a toStringmethod returns a string modifier bit pattern corresponding to FIG.

Analysis of objects using reflection at runtime

If the objects have been obtained to determine a domain object, you can call the Fieldclass get(Object obj)method to obtain the current value of the field in an object, and returns the object stored in the corresponding class.

// harry是一个员工对象,有一个域name
Employee harry = new Employee("Harry Hacker");
// 通过getClass获取harry所属的类的Class对象cl
Class cl = harry.getClass();
// 通过getDeclaredField("name")获取cl中存储的name域的Field对象f
Field f = cl.getDeclaredField("name");
// f调用get(harry)获取harry这个对象的name域的当前值,并存储在Object对象v中
Object v = f.get(harry);
// v的输出结果是Harry Hacker

Here nameis the private domain, getmethod throws illegalAccessException. Can call the setAccessiblemethod covered by Javathe access control, the default behavior of reflection is no longer limited.

f.setAccessible(true);
Writing generic code for a reflective array

Use java.lang.reflectpackage Arraymay be extended dynamically created array class. Since the element type of an array when the array is created has been recorded, you can not Objectconvert an array of objects to an array of objects of class needs. Thus, the need to use Arraya static class method newInstance(componentType, newLength)to construct an array of a desired class of objects, so that after the expansion process, this array can be converted to Objectthe class and then converted into the original class. Extended operation is as follows:

public static Object CopyOf(Object a, int newLength)
{
    // 首先获取对象a的Class对象cl
    Class cl = a.getClass();
    // 判断a是否是Array类对象
    if (!cl.isArray()) return null;
    // 确定数组对应的类型
    Class componentType = cl.getComponentType();
    // 获取数组a的长度
    int length = Array.getLength(a);
    // 构造一个和a的类型相同的新Array数组,长度为newLength
    Object newArray = Array.newInstance(componentType, newLength);
    // 将a的内容复制到新的Array数组中(有一种realloc的既视感)
    System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
    return newArray;
}
Call any method

The use of Methodclass invokemethods can call any method of the object. invokeThe signature is as follows:

// 第一个参数obj是隐式参数,对于静态方法,被设置为null,后面的显式参数表示被调用的对象数组。
Object invoke(Object obj, Object... args)

Because implicit parameter is actually Methodan object, so you need to call getMethodto get the method you want to call the Methodobject.

// 第一个参数是方法名的字符串,后面的显式参数表示方法的参数类型,用来辨别同名不同参数的方法。
Method getMethod(String name, Class... parameterTypes)

Recommended : Use only when necessary Methodobjects, it is best to use interface and lambdaexpressions.

Guess you like

Origin www.cnblogs.com/aries99c/p/12388585.html