package ReflectionDemo;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/** * 通过反射获取方法 * 并且尝试看是否符合多态的特性: 这里我会尝试重写方法以及重载方法 */public class ReflectionDemo3 { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Students stu1=new Students(); Persons stu2=new Students(); Class cls=stu1.getClass(); //下面他会获取所有的public方法,包括hello equals toString hashCode 等// System.out.println("获取的method有:");// Method[] methods = cls.getMethods();// for(Method m: methods){// System.out.println(m.getName());// } //这是通过方法名来获取方法,同时由于第二个参数我们没写 所以默认获取的是无参的hello方法 Method method=cls.getMethod("hello"); System.out.println(method.getName()); //以下两个输出一直 输出的都是Students类中的hello方法 反射同样还是遵循多态的那种写法 method.invoke(stu1); method.invoke(stu2); //这里是获取有参的hello方法 由于有参的hello方法是是有两个int类型的形参 所以要按照下面这样写 Method method2=cls.getMethod("hello",int.class,int.class); method2.invoke(stu1,1,2); //3、调用静态方法: //调用静态方法时,由于无需指定实例对象,所以invoke方法传入的第一个参数永远都是null //eg : 调用Integer.parseInt(String) 这个方法 Method method3=Integer.class.getMethod("parseInt", String.class); Object value=method3.invoke(null,"124"); System.out.println(value); }}class Students extends Persons{ int score; public void hello(){ System.out.println("Method hello in Students"); } public void hello(int num,int num2){ System.out.println(num + " Method hello in Students"); }}class Persons{ private String name; public void hello(){ System.out.println("Method hello in Person"); }}
Sign in to make a reply
张卿长