在没有构造函数的情况下运行一段代码

huangapple go评论48阅读模式
英文:

Running a piece of code without a constructor

问题

我是新手学习Java,正在编写一个GUI程序。我有一个与GUI无关的类,其中的方法我想在GUI类中使用。这些方法是静态的,我希望不必创建对象,因为它们没有任何用处。然而,为了使代码能够达到其目的,需要最初运行一段代码,似乎没有构造函数是不可能的。
所以,是否可能在不创建该类的实例的情况下运行所述代码?

英文:

I am new to java, and I'm writing a GUI program. I have a class independent of the GUI whose methods I would like to use in the GUI class. The methods are static, and I would prefer to not have objects since they would serve no purpose. However for the code to fulfill its purpose, a piece of code needs to initially run, which seems to be impossible without a constructor.
So is it possible to run said code without creating an instance of said class?

答案1

得分: 1

以下是您要翻译的内容:

您可以创建静态初始化器,它们在 JVM 的生命周期内最多运行一次,按需运行(不是在软件启动时运行,而是在您的代码尝试访问类的时候,如果尚未初始化,将在那个时间点初始化):

public final class WidgetOperations {
    private WidgetOperations() { /* 防止构造 */ }

    static {
        System.out.println("你好!我正在初始化!");
    }

    public static void foo() {
        System.out.println("FOO");
    }
}

如果您有这段代码:

void example () {
    WidgetOperations.foo();
    WidgetOperations.foo();
}

您将会看到:

你好!我正在初始化!
FOO
FOO
英文:

You can make static initializers, which are run at most once ever for the lifetime of a JVM, and are run 'as needed' (not as your software starts, but the moment your code ever tries to touch the class, if it hasn't been initialized yet, it will get initialized at that point in time):

public final class WidgetOperations {
    private WidgetOperations() { /* prevent construction */ }

    static {
        System.out.println("Hello! I am initializing!");
    }

    public static void foo() {
        System.out.println("FOO");
    }
}

if you have this code:

void example () {
    WidgetOperations.foo();
    WidgetOperations.foo();
}

you would see:

Hello! I am initializing!
FOO
FOO

答案2

得分: -1

尝试这种方法...

class Test{
     private static final Test instance = new Test();
     private Test(){//初始化代码}
     
     public static Test getInstance(){
         return instance;
     }
   
     //你的方法..
}

使用这些函数...

Test.getInstance().function();
英文:

Try this approach...

class Test{
     private static final Test instance = new Test();
     private Test(){//init code}
     
     public static Test getInstance(){
         return instance;
     }
   
     //Your methods..
}

Use the functions like..

Test.getInstance().function();

huangapple
  • 本文由 发表于 2020年7月30日 20:09:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63172884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定