-5

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?

Prudhvi Bellam
  • 71
  • 2
  • 12
  • static block get executed when class is loaded, if you want multiple times use method – Ryuzaki L Oct 03 '18 at 14:27
  • 1
    They question is, why do you want to do this? Static blocks cannot do this. How about adding the code as a static method and running the method as many times as needed? – blurfus Oct 03 '18 at 14:27
  • 1
    You can't, unless your class is loaded by multiple classloaders. It will be executed once per classloader, when either an instance of `Hello` is initialized or a static method of `Hello` is invoked. – Mena Oct 03 '18 at 14:28
  • 1
    I have clearly addressed my problem here that i have to specifically do like this yet this question has 6 downvotes. – Prudhvi Bellam Sep 27 '19 at 06:42

4 Answers4

2

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();              
            }
            }
        }

Refer Oracle Document for URLClassLoader

Prudhvi Bellam
  • 71
  • 2
  • 12
0

Static block runs when class loads, You can't run it multiple time.

Rahim Dastar
  • 1,259
  • 1
  • 9
  • 15
0

Like any other block of code that you want to execute several times you can use a loop or better to create a static function and call it several times:

public class Hello{
    public static void hello() {
        System.out.println("helloo...");
    }

    public void someMethod() {

        for(int i= 0; i < 10; i++) {
            hello();
        }
     }
}
Itamar Kerbel
  • 2,508
  • 1
  • 22
  • 29
0

You cannot. It will be run only once, when class is loads. There is one more chance you can write any number of static block in a class.

[https://beginnersbook.com/2013/04/java-static-class-block-methods-variables/][1]

arjunan
  • 217
  • 1
  • 9