How to break the Java parent-child delegate model?

In Java’s delegation model, class loaders will attempt to load classes in a specific order. If a class cannot be found in the parent class loader, the current class loader will be used to try and load it. If you need to break the delegation model, you can do so using one of the following methods:

  1. import the class
public class CustomClassLoader extends ClassLoader {
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (name.equals("com.example.MyClass")) {
            // 自定义加载MyClass类
            return defineClass(name, null, 0, 0);
        }
        return super.loadClass(name);
    }
}
  1. Set the context class loader to the current thread.
  2. Set the class loader of the current thread.
Thread.currentThread().setContextClassLoader(new CustomClassLoader());

Breaking the parent delegation model may lead to confusion and unpredictable behavior in class loading, so it is generally not recommended. Only in special scenarios, such as dynamic class updates, should breaking the parent delegation model be considered.

bannerAds