进阶day12-反射操作方法(执行访问)
This commit is contained in:
80
javaSE-day12/src/com/inmind/refelct02/MethodDemo05.java
Normal file
80
javaSE-day12/src/com/inmind/refelct02/MethodDemo05.java
Normal file
@@ -0,0 +1,80 @@
|
||||
package com.inmind.refelct02;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/*
|
||||
反射操作方法(执行访问)
|
||||
|
||||
总结:
|
||||
1.如何获取方法对象??
|
||||
通过Class对象
|
||||
Method getMethod()
|
||||
Method getDeclaredMethod
|
||||
2. 方法对象的作用:用来执行,调用,获取返回值
|
||||
|
||||
3.方法对象如何执行
|
||||
public Object invoke(Object obj, Object... args)
|
||||
参数一:要执行方法的对象(学生对象),如果是静态方法就不需要对象调用,直接给null
|
||||
参数二:调用该方法时所需的参数
|
||||
|
||||
*/
|
||||
public class MethodDemo05 {
|
||||
public static void main(String[] args) {
|
||||
//普通调用show方法
|
||||
Student s = new Student();
|
||||
/*
|
||||
一个成员方法要被执行需要哪3个要素??
|
||||
1.对象名 s
|
||||
2.方法名 show
|
||||
3.参数 ()
|
||||
*/
|
||||
s.show();
|
||||
}
|
||||
//反射获取Student类中的无参无返回值的show方法,并调用它
|
||||
@Test
|
||||
public void method1() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
|
||||
//获取class对象
|
||||
Class clazz = Student.class;
|
||||
/*
|
||||
获取无参无返回值的show方法
|
||||
Method getMethod(String name, Class<?>... parameterTypes)
|
||||
*/
|
||||
Method method = clazz.getMethod("show");
|
||||
System.out.println(method);
|
||||
|
||||
/*
|
||||
执行show方法
|
||||
public Object invoke(Object obj, Object... args)
|
||||
参数一:要执行方法的对象(学生对象),如果是静态方法就不需要对象调用,直接给null
|
||||
参数二:调用该方法时所需的参数
|
||||
*/
|
||||
method.invoke(clazz.newInstance());
|
||||
}
|
||||
|
||||
|
||||
//反射获取Student类中的私有的有参有返回值的show方法,并调用它
|
||||
@Test
|
||||
public void method2() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
|
||||
//获取class对象
|
||||
Class clazz = Student.class;
|
||||
/*
|
||||
获取私有的有参有返回值的show方法
|
||||
Method getDeclaredMethod(String name, Class<?>... parameterTypes)
|
||||
*/
|
||||
Method method = clazz.getDeclaredMethod("show", int.class);
|
||||
|
||||
method.setAccessible(true);//修改访问权限
|
||||
/*
|
||||
执行show方法
|
||||
public Object invoke(Object obj, Object... args)
|
||||
参数一:要执行方法的对象(学生对象),如果是静态方法就不需要对象调用,直接给null
|
||||
参数二:调用该方法时所需的参数
|
||||
*/
|
||||
Object result = method.invoke(clazz.newInstance(), 10);
|
||||
System.out.println(result);
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user