这个私有方法在这个单例Java类中做了什么?

kra*_*r65 3 java singleton android

我有一个单身类,功能完美.我现在只想知道最后一种方法是什么?

public class PicassoSingleton {
    private static Picasso instance;

    public static Picasso with(Context context) {
        if (instance == null) {
            instance = new Picasso.Builder(context.getApplicationContext()).debugging(true).downloader(new ImageDownloader(context)).build();
        }
        return instance;
    }

    private PicassoSingleton() {
        throw new AssertionError("No instances.");
    }
}
Run Code Online (Sandbox Code Playgroud)

有人知道它的作用或用途是什么吗?

Ren*_*ink 9

通常,使构造函数private阻止其他类实例化是足够的PicassoSingleton.

在私有构造函数中抛出异常似乎是偏执的编程,因为类的实现者知道它的内部细节并且必须知道他做了什么.

但有一个原因是有道理的.在构造函数中抛出异常也会阻止其他人使用反射来实例化该类的对象.

这是不可能的

Constructor<PicassoSingleton> constructor = PicassoSingleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance();  // will throw the AssertionError - impossible to instantiate it
Run Code Online (Sandbox Code Playgroud)