//1.根据名称获取类 Class xxxClass = Class.forName("类名"); //2.根据名称获取方法 //2.1.不带参数 Method xxxMethod = xxxClass.getMethod("方法名", new Class[]{}) //2.2.带参数 Method xxxMethod = xxxClass.getMethod("方法名", new Class[]{Long.class, String.class}) //3.调用方法 //3.1.无返回数据(是否有入参不影响) xxxMethod.invoke(xxxClass, new Object[] {}); //3.1.有返回数据(是否有入参不影响) Integer returnData = (Integer)xxxMethod.invoke(xxxClass, new Object[] { 1L, "test" });
Class xxxClass = null; try { xxxClass = Class.forName("xxx.xxx.xxx"); Integer num = (Integer) xxxClass.getMethod(funcName, new Class[]{Long.class}).invoke(xxxClass, new Object[] { 1L }); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }
Class<XXXService> xxxServiceClass = XXXService.class; try { Class<XXXService> xxxServiceClass = XXXService.class; XXXService xxxService = xxxServiceClass.getDeclaredConstructor().newInstance(); //不传参 Method func1 = xxxServiceClass.getDeclaredMethod(funcName); func1.invoke(xxxService); //传参 Method func2 = xxxServiceClass.getDeclaredMethod(funcName, Long.class); func2.invoke(xxxService, uId); //传参,有返回数据 Method func3 = xxxServiceClass.getDeclaredMethod(funcName, Long.class); Integer num = (Integer) func3.invoke(xxxService, uId); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); }
标签:调用,java,xxxClass,笔记,class,printStackTrace,catch,new,Class From: https://www.cnblogs.com/luyuting/p/16966442.html