kezhuw commented on a change in pull request #15039: URL: https://github.com/apache/flink/pull/15039#discussion_r587966568
########## File path: flink-runtime/src/test/java/org/apache/flink/runtime/metrics/util/MetricUtilsTest.java ########## @@ -243,4 +247,84 @@ public MetricGroup addGroup(String name) { METRIC_GROUP_MEMORY, METRIC_GROUP_MANAGED_MEMORY))); } + + // --------------- utility methods and classes --------------- + + /** Intercept loading classes and define them based on found class resources. */ + private static class InterceptingClassLoader extends ClassLoader { + private final Set<String> interceptingClassNames = new HashSet<>(); + private final Map<String, Class<?>> interceptedClasses = new HashMap<>(); + + public InterceptingClassLoader( + Collection<String> interceptingClassNames, ClassLoader parent) { + super(parent); + this.interceptingClassNames.addAll(interceptingClassNames); + } + + @Override + protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { + Class<?> interceptedClass = interceptedClasses.get(name); + if (interceptedClass != null) { + return interceptedClass; + } + if (!interceptingClassNames.contains(name)) { + return super.loadClass(name, resolve); + } + String classFileResourceName = name.replace('.', '/') + ".class"; + try (InputStream inputStream = getResourceAsStream(classFileResourceName)) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + IOUtils.copyBytes(inputStream, outputStream, false); + byte[] bytecode = outputStream.toByteArray(); + Class<?> definedClass = + defineClass( + name, + bytecode, + 0, + bytecode.length, + getClass().getProtectionDomain()); + interceptedClasses.put(name, definedClass); + return definedClass; + } catch (Exception ex) { + throw new ClassNotFoundException(ex.getMessage(), ex); + } + } + } + + /** Define an new class using given class's name and bytecode. */ + @SuppressWarnings("unchecked") + private static <T> Class<T> redefineAsNewClass(Class<T> clazz) throws ClassNotFoundException { + InterceptingClassLoader classLoader = + new InterceptingClassLoader( + Collections.singleton(clazz.getName()), clazz.getClassLoader()); + Class<T> newClass = (Class<T>) classLoader.loadClass(clazz.getName(), true); Review comment: Hi @zentol , this does not work in my IDEA with `java.lang.SecurityException: Prohibited package name: java.lang`, but does work in `mvn test`. The cause is that IDEA count `rt.jar` to `java.class.path`. Then it will try to load `java.lang.Object`. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org