7.9. Custom ClassLoader

download PDF
In the Microcontainer you can define a custom ClassLoader per bean. When defining a classloader for the whole deployment, make sure you don't create a cyclic dependency -- for instance, a newly defined classloader that depends on itself.

Example 7.18. Defining a ClassLoader Per Bean

<classloader><inject bean="custom-classloader:0.0.0"/></classloader>
<!-- this will be explained in future article -->
<classloader name="custom-classloader" xmlns="urn:jboss:classloader:1.0" export-all="NON_EMPTY" import-all="true"/>
<bean name="CustomCL" class="org.jboss.demos.ioc.classloader.CustomClassLoader">
  <constructor>
    <parameter><inject bean="custom-classloader:0.0.0"/></parameter>
  </constructor>
  <property name="pattern">org\.jboss\.demos\.ioc\..+</property>
</bean>
<bean name="CB1" class="org.jboss.demos.ioc.classloader.CustomBean"/>
<bean name="CB2" class="org.jboss.demos.ioc.classloader.CustomBean">
  <classloader><inject bean="CustomCL"/></classloader>
</bean>
			
			
			
			

Example 7.19, “Custom ClassLoader Test” shows a test to verify that the CB2 bean uses a custom ClassLoader, which limits the loadable package scope.

Example 7.19. Custom ClassLoader Test

public class CustomClassLoader extends ClassLoader {
    private Pattern pattern;
    public CustomClassLoader(ClassLoader parent) {
	super(parent);
    }
    public Class<?> loadClass(String name) throws ClassNotFoundException {
	if (pattern == null || pattern.matcher(name).matches())
	    return super.loadClass(name);
	else
	    throw new ClassNotFoundException("Name '" + name + "' doesn't match pattern: " + pattern);
    }
    public void setPattern(String regexp) {
	pattern = Pattern.compile(regexp);
    }
}
			
			
			
			

Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.