zxy0307's picture
Upload 2300 files
0284885 verified
Raw History Blame Contribute Delete
3.38 kB
package Reflect_package1;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class Reflect_demo4 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
/*
Class类中用于获取成员方法的方法:
Method[] getMethods ():返回所有公共成员方法对象的数组,包括继承的
Method[] getDeclaredMethods ():返回所有成员方法对象的数组,不包括继承的
Method getMethod (String name, Class<?>...parameterTypes):返回单个公共成员方法对象
Method getDeclaredMethod (String name, Class<?>...parameterTypes):返回单个成员方法对象
Method类中用于创建对象的方法
Object invoke (Object obj, Object...args) 运行方法
参数一:用obj对象调用该方法
参数二:调用方法的传递参数(如果没有就不写)
返回值:方法的返回值(如果没有就不写)
*/
//1、获取class字节码文件对象
Class<?> clazz = Class.forName("Reflect_package1.Student");
//2、获取里面所有的方法对象
Method[] methods1 = clazz.getMethods();
for (Method method : methods1) {
System.out.println(method);
}
System.out.println("=====================");
//3、获取里面所有的方法对象(不能获取父类的,但是可以获取本类私有的方法)
Method[] methods2 = clazz.getDeclaredMethods();
for (Method method : methods2) {
System.out.println(method);
}
System.out.println("=====================");
//4、获取单一的公共成员方法
Method m = clazz.getMethod("sleep");
System.out.println(m);
System.out.println("=====================");
//5、获取单一的成员方法
Method e = clazz.getDeclaredMethod("eat", String.class);
System.out.println(e);
System.out.println("=====================");
//6、获取方法的修饰符
int modifiers = m.getModifiers();
System.out.println(modifiers);
//获取方法的名字
String name = m.getName();
System.out.println(name);
//获取方法的形参
Parameter[] parameters = e.getParameters();
for (Parameter parameter : parameters) {
System.out.println(parameter);
}
System.out.println("=====================");
//7、获取方法抛出的异常
Class<?>[] exceptionTypes = m.getExceptionTypes();
for (Class<?> exceptionType : exceptionTypes) {
System.out.println(exceptionType);
}
//方法运行
// Object invoke (Object obj, Object...args) 运行方法
// 参数一:用obj对象调用该方法
// 参数二:调用方法的传递参数(如果没有就不写)
// 返回值:方法的返回值(如果没有就不写)
Student s = new Student();
e.setAccessible(true);//忽略权限
Object result = e.invoke(s, "汉堡包");
System.out.println(result);
}
}