Learn reflection with teacher Wang (vi): Using reflection to invoke a method teacher: Wang Shaohua QQ Group No.: 483773664 Learning Content
Calling methods using Reflection
When you get the class object for a category, you can get all methods or methods by using the class object's GetMethods () method or the GetMethod () method, and the return value of the two methods is either an array of method objects or a method object.
One, public object invoke (Object obj, object ... args)
Once the method object is obtained, the program can call the corresponding methods by means of the approach, including an invoke method in the method.
Obj In this method is the object that executes the method, and the following args is the parameter that is passed in when the method is executed
Use parameters args
to obj
Assign the result of the method represented on the object
Ii. Examples of invocation methods
12345678910 |
public static void test4()
throws Exception{
Class<Person> personClass = Person.
class
;
Person person = personClass.newInstance();
//得到setName方法
Method method = personClass.getMethod(
"setName"
, String.
class
);
//调用setName,为name赋值
Object object = method.invoke(person,
"wangwu"
);
System.out.println(person);
System.out.println(object);
}
|
Third, the matters needing attention
When invoking the method by means of the Invoke method, Java will require the program must have permission to invoke the method, if the program does need to call the private method of an object, you can call the method object as follows
public void Setaccessible (Boolean flag): Sets the accessible flag of this object to the indicated Boolean value. A value of TRUE indicates that the reflected object should cancel the Java language access check when it is used. A value of false indicates that the reflected object should implement a Java language access check.
public boolean isaccessible (): Gets the value of the accessible flag for this object.
123 |
private void setName(String name) { this .name = name; } |
1234567891011121314 |
public static void test5()
throws Exception{
Class<Person> personClass = Person.
class
;
Person person = personClass.newInstance();
//得到setName方法
Method method = personClass.getDeclaredMethod(
"setName"
, String.
class
);
//调用访问权限检查
if
(!method.isAccessible()){
method.setAccessible(
true
);
}
//调用setName,为name赋值
Object object = method.invoke(person,
"wangwu"
);
System.out.println(person);
System.out.println(object);
}
|
From for notes (Wiz)
Learn from teacher Wang Reflection (vi): Invoking Methods with Reflection