如何在java中多次执行静态块

我给了一个任务,每 20 秒执行一次静态块。我有一个由静态块组成的类。


public class Hello{

      static{

        System.out.println("helloo...");

      }

}

我知道静态块在类加载时执行。


但我想知道有没有办法多次执行静态块以及如何执行?


弑天下
浏览 497回答 3
3回答

holdtom

执行静态块可以通过使用自定义类加载器来实现。类重载文件&nbsp; &nbsp; Class<?> load = ClassLoader.getSystemClassLoader().loadClass("com.Hello");//Assume Hello class is in "com" package&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; load.newInstance().toString();&nbsp; &nbsp; &nbsp; &nbsp; URL[] urls = { load.getProtectionDomain().getCodeSource().getLocation() };&nbsp; &nbsp; &nbsp; &nbsp; ClassLoader delegateParent = load.getClassLoader().getParent();&nbsp; &nbsp; &nbsp; &nbsp; try (URLClassLoader cl = new URLClassLoader(urls, delegateParent)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class<?> reloaded = cl.loadClass(load.getName());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reloaded.newInstance().toString();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }

噜噜哒

静态块在类加载时运行,您不能多次运行它。

Qyouu

与您想要多次执行的任何其他代码块一样,您可以使用循环或更好地创建静态函数并多次调用它:public class Hello{&nbsp; &nbsp; public static void hello() {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("helloo...");&nbsp; &nbsp; }&nbsp; &nbsp; public void someMethod() {&nbsp; &nbsp; &nbsp; &nbsp; for(int i= 0; i < 10; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hello();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java