java(4)-反射之调用方法

//        Method getMethod(name, Class...):获取某个public的Method包含父类, Class为参数类型
//        Method getDeclaredMethod(name, Class):获取某个public的Method不包含父类
//        Method[] getMethods()
//        Method[] getDeclaredMethods()
        Class cls = Person.class;
        System.out.println(cls.getMethod("getName"));
    }
}

class Person
{
    public String getName()
    {
        return "Person";
    }
}

       // 多态
        // 获取Person的hello方法:
        Method h = Person.class.getMethod("hello");
        // 对Student实例调用hello方法:
        h.invoke(new Student());

        //通过Method实例可以获取方法信息:
        // getName(),getReturnType(),getParameterTypes(),getModifiers();

        //调用静态方法:由于没有实例,所以第一个实例参数填为null
        Method m = Integer.class.getMethod("parseInt", String.class);
        Integer n = (Integer) m.invoke(null, "13");
        System.out.println(n);

        //调用非public 方法
        m.setAccessible(true);

        //调用方法:invoke(实例, 参数)
        String s = "hello";
        Class cls = s.getClass();
        m = cls.getMethod("substring", int.class, int.class);
        String r = (String) m.invoke(s, 2,3);
        System.out.println(r);

    }
}

class Person {
    public void hello() {
        System.out.println("Person:hello");
    }
}

class Student extends Person {
    public void hello() {
        System.out.println("Student:hello");
    }
}

练习:


public class hello {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        String name = "Xiao Ming";
        int age = 20;
        Person p = new Person();
        // TODO: 利用反射调用setName和setAge方法:
        Class cls = p.getClass();
        Method m = cls.getMethod("setName", String.class);
        m.invoke(p, "Xiao Ming");
        Method n = cls.getMethod("setAge", int.class);
        n.invoke(p, 20);
        System.out.println(p.getName()); // "Xiao Ming"
        System.out.println(p.getAge()); // 20
    }
}

class Person {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}
发布了89 篇原创文章 · 获赞 0 · 访问量 1635

猜你喜欢

转载自blog.csdn.net/qq_43410618/article/details/104409595