Reputation: 13
In my java program, I have a class with static block. I know that static blocks are initialized only once and loaded only once by JVM. But what if I want that static block to be executed(Or Loaded) more than one times . I have tried to dynamic load that class in another class using class.forName() and also tried using classLoader. But Static block is executing only once. So suggest me simplest way of doing it.
I came to know about the fact that by using classLoader we can load multiple version of same class. but how? Can I implement that concept in my program.
Upvotes: 1
Views: 420
Reputation: 2959
The following is a rough sketch of the classloader you need
class HelloWorldClassLoader extends ClassLoader {
@Override
public Class loadClass(String name) throws ClassNotFoundException {
if (!"MyClass".equals(name)) return super.loadClass(name);
byte[] bb=ByteStreams.toByteArray(
getResourceAsStream(name.replace('.','/')+".class"));
return defineClass(name,bb,0,bb.length);
}
}
To use it, do
new HelloWorldClassLoader().loadClass("MyClass");
Upvotes: 2
Reputation: 36
Response for similar question is provided in stackoverflow below are some links: Java - how to load different versions of the same class?
Upvotes: 0