Java detect that code has been hot swapped in

467 Views Asked by At

bizarre question - but I'm wondering how I'd write code to basically say "have any classes been hotswapped by intellij since I last checked"

why?

For evil historical reasons - the springcontext is taking 2-3 minutes to start up, which means if you just want to run a single test, that's 2-3 minutes of wait time. If you are a TDD person, who wants to write a bit, run, write a bit, run - it's unworkable. Speeding up the springcontext loading is obviously the ideal, but way beyond the time I have as it's all a mess - what I'm thinking is just to make a junit test which is an infinite loop:

while true
    try {run the actual test;show success} catch {show error}
    wait until code is hot swapped

so that way, a lot of the time, someone can just write a bit of code, press the build key - and it will immediately get run again without a reload of the context - taking a 2-3 minutes delay down to less than a second.

1

There are 1 best solutions below

0
On

Have a look at HotswapAgent, Java unlimited runtime class and resource redefinition.

Download dcevm and latest hotswap-agent-core.jar and run your application with java --javaagent:c:\java\hotswap-agent-core.jar YourApp.

Add HotswapAgent dependency:

    <dependency>
        <groupId>org.hotswapagent</groupId>
        <artifactId>hotswap-agent-core</artifactId>
        <version>1.3.0</version>
        <scope>provided</scope>
    </dependency>

You will need also Hotswap Agent plugins to reload Spring and other beans/caches:

        <dependency>
            <groupId>org.hotswapagent</groupId>
            <artifactId>hotswap-agent-plugins</artifactId>
            <version>1.3.0</version>
            <type>pom</type>
        </dependency>

Write your plugin class:

    @Plugin(name = "TriggerHotswapPlugin")
    public class TriggerHotswapPlugin {

        @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
        public static void onAnyReload() {
            .. synchronization mechanism with your class .. ;
        }

        @OnResourceFileEvent(path = "/", filter = ".*.resource")
        public void onResourceChanged() {
            .. synchronization mechanism with your class .. ;
        }
    }

Create hotswap-agent.properties

    pluginPackages=your.plugin.package

As an alternative, you can create simple javaagent to trigger hotswap, but you need full hotswap of java classess anyway, why not to write custom hotswap agent plugin.