Java Singleton内部类 [英] Java singleton inner class

查看:113
本文介绍了Java Singleton内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java中单例的概念. 我在用Java创建单例作为内部类时遇到问题.问题发生在持有人的

I know the concept of singleton in Java. I'm having problems with creating singleton as inner class in Java. Problem occurs at holder's

public class NormalClass {
    private class Singleton {
        private static Singleton instance = null;

        private Singleton() {
        }

        private static class SingletonHolder {
            private static Singleton sessionData = new Singleton();
        }

        public static Singleton getInstance() {
            return NormalClass.Singleton.SingletonHolder.sessionData;
        }
    }

    public void method1() {
        Singleton.getInstance();
    }
}

在新的Singleton()构造函数调用中出现错误.如何将Singleton的私有构造函数正确地调用为内部类?

Error is at new Singleton() constructor call. How to proper call private constructor of Singleton as inner class?

致谢

推荐答案

如果它应该是真正的单例,请将您的单例类设为静态.然后,您将可以调用构造函数.

If it should be a real singleton, make your singleton class static. Then you will be able to call the constructor.

Java中解释了构造函数调用不起作用的原因.嵌套类教程.基本上,内部类在构造之前需要外部类的实例:

The reason why your constructor call does not work is explained in the Java nested classes tutorial. Basically, the inner class requires an instance of the outer class before it can be constructed:

private static Singleton sessionData = new NormalClass().new Singleton();

这篇关于Java Singleton内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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