Reflect,围着大Class转
//基本数据类型或者类类型获得大Class Class<Integer> integerClass = int.class; Class<Student> studentClass = Student.class; //对象(引用)获得大Class,它是调用getClass()方法 Student stu = new Student(); Class<? extends Student> aClass = stu.getClass();//这句代码的含义就是:stu引用在运行时所指向对象的实际类型
反射会报编译时异常,例如NoSuchMethodException,预防方法找不到的情况,上代码:
public class ReflectTest { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { //获得大Class Student stu = new Student("tom",18,1); Class<? extends Student> aClass = stu.getClass(); //获得名叫toString的方法,因为toString不用传参数,所以参数类型写null Method m1 = aClass.getMethod("toString", null); //invoke是执行方法的意思,stu对象调用m1这个方法,没有参数 Object result = m1.invoke(stu, null); //上面两行相当于传统的Object s = stu.toString(); System.out.println(result); System.out.println("---------------"); //以下两行相当于stu.sayHello("briup"); Method m2 = aClass.getMethod("sayHello", String.class); Object result2 = m2.invoke(stu, "briup"); //这里的sayHello方法因为返回值是void,所以打印result2是null } }