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
Method
objects.
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, Class
responsible for information preservation class, not the object. Virtual machine type information to select the appropriate method for runtime execution.
In Object
class getClass
method returns an Class
instance of a type. Therefore, you can make a call to an object getClass
method to obtain information about the object belongs. One of the most common class name can getName
be obtained method, where the bags are also included in the class name.
// 假设e是某个类的实例
System.out.println(e.getClass().getName());
Conversely, by forName
obtaining method corresponding to the class name Class
examples.
// 这里要获取Random的Class实例,注意包名
Class cl = Class.forName("java.util.Random");
// 如果输入的类名不存在,会抛出“已检查异常”ClassNotFoundException。
There is a very simple way to get the Class
class object, that is, directly or type in Java void
after 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 Class
three methods class object.
Gets Class
the class object, you can call the newInstance
method 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 Constructor
class newInstance
method.
Analysis of the ability to reflect the use of the class
In java.lang.reflect
classes in a package Field
, Method
and Constructor
fields, methods and constructors for the class description. Modifier
Class provides static
methods and constants, can decode class and member access modifiers.
In Class
class getXXX
method and getDeclaredXXX
is 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: Constructor
and Method
class getParameterTypes
methods can return type constructor parameter or method Class
object array. Method
Class getReturnType
method returns the method's return type of the parameter Class
object.
In Modifier
There are a number of classes static boolean
a method for detection method modifier. getModifiers
Method returns the modifier int
bit pattern memory , each represents a modifier. Modifier
Class also provides a toString
method 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 Field
class 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 name
is the private domain, get
method throws illegalAccessException
. Can call the setAccessible
method covered by Java
the access control, the default behavior of reflection is no longer limited.
f.setAccessible(true);
Writing generic code for a reflective array
Use java.lang.reflect
package Array
may be extended dynamically created array class. Since the element type of an array when the array is created has been recorded, you can not Object
convert an array of objects to an array of objects of class needs. Thus, the need to use Array
a 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 Object
the 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 Method
class invoke
methods can call any method of the object. invoke
The signature is as follows:
// 第一个参数obj是隐式参数,对于静态方法,被设置为null,后面的显式参数表示被调用的对象数组。
Object invoke(Object obj, Object... args)
Because implicit parameter is actually Method
an object, so you need to call getMethod
to get the method you want to call the Method
object.
// 第一个参数是方法名的字符串,后面的显式参数表示方法的参数类型,用来辨别同名不同参数的方法。
Method getMethod(String name, Class... parameterTypes)
Recommended : Use only when necessary Method
objects, it is best to use interface and lambda
expressions.