Original link: Little Ben Horse's Java Reflection (reflection) Basics Explained
1. How to get the class object 1.1
Class#forName
publicstaticforNamethrows ClassNotFoundException;
Throws an exception if the class object is not obtained ClassNotFoundException
;
eg
Class<?> customerClazz = Class.forName("cn.xiaobenma.demo.core.reflection.VipCustomer");
1.2 of a class
.class
, eg:
Class<?> customerClazz = VipCustomer.class;
1.3 of an Object
getClass()
, eg:
newVipCustomer("001""小ben马""10086", VipCustomer.VIP_ADVANCED);Class<?> customerClazz = customer.getClass();
2. Determine if an instance of a class
We usually use it instanceof
to determine whether an object is an instance of a class. Again, you can use it Class#isInstance()
to judge
publicnativebooleanisInstance(Object obj);
Example:
booleaninstanceof VipCustomer;isCustomer = VipCustomer.class.isInstance(customer);
If person is null, the above example returns FALSE.
3. Create an Instance 3.1
Class#newInstance()
: To ensure access to the non-parametric construction method of the class
publicnewInstancethrows InstantiationException, IllegalAccessException;
3.2 by
Constructor#newInstance(Object ... initargs)
publicnewInstance... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
eg
getVipCustomerClass().getConstructor(String.class, String.class, String.classint.class); VipCustomer customer = constructor.newInstance("001""小ben马""10086", VipCustomer.VIP_ADVANCED);
4. Get method (class method, member method) 4.1 class#getmethods ()
Gets the current class and its parent class, all public
class methods and Member Methods
4.2 Class#getmethod (String name, Class<?> .... parametertypes)
Gets a single public
class method or member method (defined by the current class or parent Class) by method name, parameter type
4.3 class#getdeclaredmethods ()
Gets all class methods and member methods defined by the current class (excluding superclass)
4.4 Class#getdeclaredmethod (String name, Class<?> .... parametertypes)
Gets a class method or member method defined by a single current class (excluding superclass) by method name, parameter type
5. Get the Construction Method 5.1 class#getconstructors ()
Gets all the constructor methods for the current class public
5.2 Class#getconstructor (class<?> ... parametertypes)
Gets the current class individual construction method based on the parameter type public
5.3 Class#getdeclaredconstructors ()
Gets all the constructor methods for the current class
5.4 Class#getdeclaredconstructor (class<?> ... parametertypes)
Gets the current class individual construction method based on the parameter type
6. Get variables (class variables, member variables) 6.1 Class#getfields ()
Gets the current class and its superclass, all public
class variables and member variables
6.2 Class#getfield (String name)
By name, gets the current class or superclass, a single public
class variable, or a member variable
6.3 Class#getdeclaredfields ()
Gets the current class (excluding the superclass), all class variables and member variables
6.4 Class#getdeclaredfield (String name)
By name, gets the current class (excluding the superclass), a single class variable or member variable
7. By
Method#invoke(Object obj, Object... args)
, the method that invokes the object
eg
getVipCustomerClass().getDeclaredMethod("setRank"int.class);setRank.invoke(customer, VipCustomer.VIP_NORMAL);
8. Get and modify the value of a class variable or member variable 8.1 field#set (object obj, Object value)
Set variables by object and variable values, eg:
getVipCustomerClass().getDeclaredField("rank");field.set(customer, VipCustomer.VIP_ADVANCED);
8.2 field#get (Object obj)
Get variable values by object, eg:
getVipCustomerClass().getDeclaredField("rank");int rank = (int) field.get(customer);
9. Dynamic change of the accessibility of methods and variables
When using reflection to get the constructor method, method, or variable of the called class, it is possible that the calling class is inaccessible, such as the constructor method, method, and variable of the called Class, which is private
private
private
thrown IllegalAccessException
.
Java can change accessibility by using AccessibleObject#setAccessible(boolean flag)
.
Constructor
, Method
and Field
all AccessibleObject
of the subclasses.
eg
//define class static constants in Vipcustomer pri_no=100Field field =Getvipcustomerclass().Getdeclaredfield("Pri_no"); field.setaccessible(true); Assert.assertequals( -, field.Get(NULL));//Private construction methodConstructor<vipcustomer> Constructor =Getvipcustomerclass().Getdeclaredconstructor(); constructor.setaccessible(true); Vipcustomer customer = constructor.newinstance(); Assert.Assertnull(Customer.Getcustomerno()); Assert.Assertnull(Customer.GetName()); Assert.Assertnull(Customer.Getmobilephone());//Call private class methodMethod method =Getvipcustomerclass().Getdeclaredmethod("Donothingbyvipcustomer"); method.setaccessible(true); method.Invoke(NULL);
10. Creating an array with reflection
Arrays are relatively special types.
10.1 array#newinstance (class<?> componenttype, int length)
Create a one-dimensional array, eg:
//一维数组Object array = Array.newInstance(String.class2);Array.set0"小ben马");Array.set1"xiaobenma");Assert.assertEquals("小ben马", Array.get0));Assert.assertEquals("xiaobenma", Array.get1));
10.2 array#newinstance (class<?> componenttype, int ... dimensions)
Create a multidimensional array, eg:
//Multidimensional Arrays//string[2][1]Object arrays = Array.newinstance(String.class,2,1); Object array0 = Array.newinstance(String.class,1); Array.Set(Array0,0,"Little Ben Horse."); Array.Set(Arrays,0, array0); Object array1 = Array.newinstance(String.class,1); Array.Set(Array1,0,"Xiaobenma"); Array.Set(Arrays,1, array1); Assert.assertequals("Little Ben Horse.", Array.Get(Array.Get(Arrays,0),0)); Assert.assertequals("Xiaobenma", Array.Get(Array.Get(Arrays,1),0));
10.3 Array#get (Object Array, int index)
Get corresponding values based on arrays and related indexes
10.4 Array#set (object Array, int index, object value)
Set the corresponding value based on the index and the associated index
11.Modifier description
Typically in a class
- Defines the construction method format
[修饰符列表] 类名([参数列表])
.
- The format of the definition variable is
[修饰符列表] 返回类型 变量名称
.
- The format of the definition method is
[修饰符列表] 返回类型 方法名([参数列表])
.
Member#getModifiers()
Returns an int that can get a list of defined modifiers by interpreting the value of int. Constructor
, Method
and Field
Member
the implementation classes that are both.
The int value returned by the modifier needs to be Modifier
interpreted.
which
Modifier#toString(int mod)
: Print all the modifiers defined
Modifier#isXXX(int mod)
: Determine the type of modifier
If you have read Modifier
the source code, you will find an interesting thing, modifiers are bitwise bit
defined, such as:
/*** the{@code int}value representing the{@code Public}* modifier. */ Public Static Final intpublic =0x00000001;/*** the{@code int}value representing the{@code Private}* modifier. */ Public Static Final intPRIVATE =0x00000002;/*** the{@code int}value representing the{@code protected}* modifier. */ Public Static Final intPROTECTED =0x00000004;
PS Description
- Reflection-related Packages
java.lang.reflect
Proxy
is a more important application in reflection and is updated separately in subsequent blogs.
- Related Demo Code core-java-learning
Java Reflection (reflection) Basics