try { File file = new File("C:\\Users\\classes\\com\\test"); URL[] urls = {file.toURI().toURL()}; URLClassLoader urlClassLoader = new URLClassLoader(urls); Class clazz = urlClassLoader.loadClass("Foo"); java.lang.Object fooObject = clazz.newInstance(); java.lang.reflect.Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i ++) { java.lang.reflect.Field field = fields[i]; String name = field.getName(); System.out.println("field->" + name); } Method computeFreightFeeMethod = null; java.lang.reflect.Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i ++) { Method method = methods[i]; String name = method.getName(); System.out.println("method->" + name); if (name.equals("computeFreightFee")) { computeFreightFeeMethod = method; } } if (computeFreightFeeMethod != null) { Class[] parameterTypes = computeFreightFeeMethod.getParameterTypes(); int parameterCount = computeFreightFeeMethod.getParameterCount(); System.out.println("打印参数数量->" + parameterCount); for (int i = 0; i < parameterTypes.length; i ++) { System.out.println("打印参数类型->" + parameterTypes[i].toString()); } Object result = computeFreightFeeMethod.invoke(fooObject, 1); Integer fee = (Integer) result; System.out.println("fee->" + fee); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException illegalAccessException) { illegalAccessException.printStackTrace(); } catch (InstantiationException instantiationException) { instantiationException.printStackTrace(); } catch (InvocationTargetException invocationTargetException) { invocationTargetException.printStackTrace(); }
java从磁盘加载class反射调用方法
最新推荐文章于 2022-09-07 14:33:23 发布