为什么要为单例Java类创建两个实例? [英] Why are there two instances created of a singleton Java class?

查看:75
本文介绍了为什么要为单例Java类创建两个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Internet上浏览了一些相关主题,例如

因此,它必须与android以及项目中如何加载类有关.

I have gone through some related topics on internet like this and questions here like this, this and this, but I'm getting nowhere. Here is my simplified code:

MainActivity:

package com.test.staticvariables;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Test1 test1 = Test1.getInstance();
    // do something
    Test2.printTest1Instances();
  }
}

Test1:

package com.test.staticvariables;

public class Test1 {

  private static Test1 test1;

  static {
    System.out.println("Initializing Test1, loader: " + " " + Test1.class.getClassLoader());
  }

  static synchronized Test1 getInstance() {
    if (test1 == null) {
      test1 = new Test1();
    }
    return test1;
  }

  private Test1() {}
}

Test2:

package com.test.staticvariables;

public class Test2 {

  private static final Test1 test1;
  // private static final Test1 test1 = Test1.getInstance();
  // private static final Test1 test1 = getTest1Instance();

  static {
    System.out.println("Initializing Test2, loader: " + " " + Test2.class.getClassLoader());
    test1 = Test1.getInstance();
  }

  static Test1 getTest1Instance() {
    return Test1.getInstance();
  }

  private Test2() {}

  static void printTest1Instances() {
    System.out.println("Test1 class variable: " + test1);
    System.out.println("Test1 instance variable: " + Test1.getInstance());
  }
}

Result:

Initializing Test1, loader: dalvik.system.PathClassLoader[DexPathList...]
Initializing Test2, loader: dalvik.system.PathClassLoader[DexPathList...]
Test1 class variable: com.test.staticvariables.Test1@2a7bfa4
Test1 instance variable: com.test.staticvariables.Test1@7e2a464

Why are two instances created of class Test1 (2a7bfa4 and 7e2a464)?

Please note that Test2 only contains static methods, it's not being instantiated.

The app runs in a single native process, so the classes should be loaded by the same class loader (if I understand it correctly).

Declaring and initializing (inside or outside a static method or a static initialization block) a final static variable holding other class instance is a wrong / bad practice? Or is it wrong under certain situations?

解决方案

It seems like very interesting question. I have run the same project but directly from public static void main and it returned the expected good results. Nothing broken.

So it must have to do with android and how classes are loaded on your project.

这篇关于为什么要为单例Java类创建两个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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