1

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.

Jasmita
  • 13
  • 3
  • Have you tried writing your own class loader?. `class.forName()` checks if the class has already been loaded.. So it won't help you – TheLostMind Jan 29 '15 at 13:02
  • 1
    if you will write your own ClassLoader then it can be. otherwise system classloader is checking that class has been loaded or not if yes then don't load class only return class object for your class type. – Prashant Jan 29 '15 at 13:05
  • What is your actual use case? – PM 77-1 Jan 29 '15 at 13:06
  • put up your classloaders implementation. – Rahul Winner Jan 29 '15 at 18:44
  • Thanks to all for your valuable suggestions. Yes , you guys were right . It can be done only by writing own classLoader. – Jasmita Jan 30 '15 at 07:49

2 Answers2

2

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");
ruediste
  • 2,434
  • 1
  • 21
  • 30
0

Response for similar question is provided in stackoverflow below are some links: Java - how to load different versions of the same class?

Community
  • 1
  • 1
ashishdna
  • 36
  • 4