Search code examples
javaosgiaemassertosgi-bundle

How to enable assert in CQ5/ OSGi Bundle (Java)?


We enable asserts in a core java application by doing java -ea xxx, I also know how to enable assertions in eclipse by changing the commandline options.

But how to enable assert in an OSGi bundle. I have a bundle that I want to test with assertions enabled and I want to disable them at the time of deployment(Disabling would be easy as assert is disabled by default). But how to enable it ?


Solution

  • You may use the ClassLoader#setDefaultAssertionStatus(Boolean) method. It sets the assertion status only for classes that hasn't been loaded yet. Therefore, the best place to put this statement would be a bundle activator:

    public class Activator implements BundleActivator {
    
        @Override
        public void start(BundleContext bundleContext) throws Exception {
            getClass().getClassLoader().setDefaultAssertionStatus(true);
        }
    
        @Override
        public void stop(BundleContext context) throws Exception {
        }
    }
    

    Remember to register the activator in the maven-bundle-plugin configuration:

    <project>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <configuration>
              <instructions>
                <Bundle-Activator>my.project.Activator</Bundle-Activator>
    ...