简体   繁体   English

从活动引用私有帮助程序类

[英]Referencing private helper class from activity

I need to use some methods from a helper class but having trouble when I try to create a object of the helper class in my activity. 我需要使用辅助类中的一些方法,但是当我尝试在我的活动中创建辅助类的对象时遇到麻烦。

HelperClass helper = new HelperClass();

When I do the above I get an error saying I need to make the visibility of Helper() default. 当我执行上述操作时,我收到一条错误消息,说我需要将Helper()的可见性设置为默认值。 Here is the relevant part of the helper class. 这是助手类的相关部分。

public class HelperClass {

private static HelperClass helperClass;
private String list;

private HelperClass() {
    initialiseHelper();
}

When I take out the private in the HelperClass it is fine but I do not want to edit this class. 当我在HelperClass中取出私有时它很好,但我不想编辑这个类。 Is there a way around this? 有没有解决的办法?

It looks like you're trying to apply Singleton pattern, but you're missing the getInstance() method, which should look like this: 看起来您正在尝试应用Singleton模式,但是您缺少getInstance()方法,它应该如下所示:

public static synchronized HelperClass getInstance() {
    if (helperClass == null) {
        helperClass = new HelperClass();
    }
    return helperClass;
}

Now you should use this method everywhere you want to reference an instance of HelperClass . 现在,您应该在任何想要引用HelperClass实例的地方使用此方法。 Hope this helps. 希望这可以帮助。

如果你想要私有构造函数你可以从HelperClass制作单例。

Your Helper class does not have a public constructor as you have marked it private . 您的Helper类没有public构造函数,因为您已将其标记为private

Or 要么

public HelperClass{

   private HelperClass(){
   // do some stuff
   }

   public static HelperClass newInstance(){
       new HelperClass();
   }
}

Or use Singleton Pattern 或者使用Singleton Pattern

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM