在Java中的静态块中创建对象的优缺点是什么? [英] What are the advantages and disadvantages of creating an Object in static block in Java?

查看:105
本文介绍了在Java中的静态块中创建对象的优缺点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某些Java专家来说,这个问题可能是个错误.但是我想知道为什么我们要像main这样的静态方法而不是static块中创建对象.我知道,如果我们在静态块中实例化它,并且如果不进一步使用它,它将不必要地创建该对象.使用此方法还有其他需要注意的事项吗?我们可以将其与单例模式相关吗?

This question might be blunder to some of the Java Experts. But I would like to know why we create the objects in a static method like main but not in static block. I understand that its going to create the object unnecessarily if we instantiate in static block and of course if we don't use it further. Are there any other things that are to be noted with this approach ? Can we relate this with Singleton Pattern ?

例如:

public class MyClass {

    static {
        AnotherClass object = new AnotherClass();
            // Do Some operations here with object.
    }
}

推荐答案

主要原因是控制它何时真正被执行.静态块中的内容将在第一次加载该类时执行,并且很容易意外地导致一个类被加载(例如,通过引用该类上的常量).

The main reason is control over when it actually gets executed. The stuff in a static block will get executed the first time that the class is loaded and it's easy to accidentally cause a class to be loaded (for instance by referencing a constant on the class).

拥有静态方法意味着您可以完全控制何时调用该方法(因为必须显式调用它).

Having a static method means that you have complete control over when the method is called (because you have to explicitly call it).

关于单例,急于加载的单例的Java惯用法将实例初始化为静态字段.这基本上将与静态块相同.

In regards to singletons, the java idiom for eagerly loaded singletons initializes the instance as a static field. This will basically run just the same as a static block.

public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

这篇关于在Java中的静态块中创建对象的优缺点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆