JavaMethod类及invoke方法的用法-创新互联
这篇文章主要讲解了Java Method类及invoke方法的用法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

在说Method和invoke的使用之前我们来看一个小例子, 如果看懂了那就ok了
public class MethodInvoke {
class Animal {
public void print() {
System.out.println("Animal.print()");
}
}
class Cat extends Animal {
@Override
public void print() {
System.out.println("Cat.print()");
}
}
public static void main(String[] args) throws Exception {
Method animalMethod = Animal.class.getDeclaredMethod("print");
Method catMethod = Cat.class.getDeclaredMethod("print");
Animal animal = new Animal();
Cat cat = new Cat();
animalMethod.invoke(cat); //相当于 cat调用父类的print方法
animalMethod.invoke(animal);//相当于 animal.print();
catMethod.invoke(cat); //相当于 cat.print();
catMethod.invoke(animal);
}
} 分享文章:JavaMethod类及invoke方法的用法-创新互联
URL地址:http://www.jxjierui.cn/article/dceshi.html


咨询
建站咨询
