I have given a task to execute static block for every 20 seconds. I have a class that consists of a static block.
public class Hello{
static{
System.out.println("helloo...");
}
}
I know that static block executes when the class is loaded.
But i want to know is there any way to execute the static block for multiple times and how?
Executing a Static Block can be Achieved by using Custom Class Loader.
ClassReload.java
Class<?> load = ClassLoader.getSystemClassLoader().loadClass("com.Hello");
//Assume Hello class is in "com" package
load.newInstance().toString();
URL[] urls = { load.getProtectionDomain().getCodeSource().getLocation() };
ClassLoader delegateParent = load.getClassLoader().getParent();
try (URLClassLoader cl = new URLClassLoader(urls, delegateParent)) {
Class<?> reloaded = cl.loadClass(load.getName());
reloaded.newInstance().toString();
}
}
}