标签:invoke stack java 反射 string null 反射 exception static param
反射(Reflection): 在多个类没有公共特性时,
可以在一个基类方法中,
通过反射,
实现对这些没有公共特性的类的普遍性调用。
①//getMethod(String name, Class<?>... parameterTypes)
Method method = class.getMethod("要调用的方法名称","要调用的方法的形参的类型的class");
②//invoke(Object obj, Object... args)
method.invoke("对象实例","要调用的方法的形参");
1 public class ReflectiveTest { 2 3 public static void reflectiveMethod(Object object) { 4 5 System.out.println("-------------反射使用方法--------------"); 6 7 Class<?> clazz = object.getClass(); 8 try { 9 10 //getMethod():第一个参数方法名称;第二个参数:方法的形参的class 11 Method sitMethod = clazz.getMethod("sit",null); 12 sitMethod.invoke(object,null); 13 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { 14 e.printStackTrace(); 15 } 16 17 18 try { 19 Method eatMethod = clazz.getMethod("eat",String.class); 20 eatMethod.invoke(object,"pork"); 21 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { 22 e.printStackTrace(); 23 } 24 25 try { 26 27 Method calculateMethod = clazz.getMethod("calculate",int.class,int.class); 28 int a = (Integer) calculateMethod.invoke(object,1024,2048); 29 System.out.println("calculateMethod 结果=" + a); 30 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { 31 e.printStackTrace(); 32 } 33 34 } 35 36 37 public static void main(String[] args) { 38 39 Dog dog = new Dog(); 40 Robot robot = new Robot(); 41 42 reflectiveMethod(dog); 43 reflectiveMethod(robot); 44 } 45 46 47 }
运行结果:
1 -----------------反射使用方法------------------- 2 Dog sits 3 Dog eats pork 4 java.lang.NoSuchMethodException: com.wing.test.vo.Dog.calculate(int, int) 5 at java.lang.Class.getMethod(Class.java:1786) 6 at com.wing.test.ReflectiveTest.reflectiveMethod(ReflectiveTest.java:41) 7 at com.wing.test.ReflectiveTest.main(ReflectiveTest.java:56) 8 java.lang.NoSuchMethodException: com.wing.test.vo.Robot.eat(java.lang.String) 9 at java.lang.Class.getMethod(Class.java:1786) 10 at com.wing.test.ReflectiveTest.reflectiveMethod(ReflectiveTest.java:33) 11 at com.wing.test.ReflectiveTest.main(ReflectiveTest.java:57) 12 -----------------反射使用方法------------------- 13 Robot sits 14 Robot calculates a + b = 3072 15 calculateMethod 结果=3072
辅助类:
1 public class Dog { 2 3 public Dog() { 4 } 5 6 public void sit(){ 7 System.out.println("Dog sits "); 8 } 9 10 public void eat(String meat){ 11 System.out.println("Dog eats " + meat); 12 } 13 14 15 } 16 17 18 public class Robot { 19 20 public Robot() { 21 } 22 23 public void sit(){ 24 System.out.println("Robot sits"); 25 } 26 27 public int calculate(int a,int b){ 28 int c = a + b; 29 System.out.println("Robot calculates a + b = " + c); 30 return c; 31 } 32 33 }
标签:invoke stack java 反射 string null 反射 exception static param
原文地址:https://www.cnblogs.com/BenNiaoXianFei/p/12658654.html