1

想在静态主要中使用非静态方法,但我不能。我知道这个问题,但是因为我使用 INotificationObserver,所以我不能将 registerObserver 设为静态。所以我可以解决我的问题。

我怎么解决这个问题 ??谢谢 。

非静态变量 this 不能从静态上下文中引用

测试

   public class PushTest implements INotificationObserver{    
   NotificationService ns = NotificationService.getInstance(); 

    public static void main(String[] args) {         
        try {                        
            ns.registerObserver(this); // How can i register ???

界面

public interface INotificationSubject {
    public  void registerObserver(INotificationObserver o);
    public void removeObserver(INotificationObserver o);
    public void notifyObserver(PushedNotification notification);
}

*通知服务 *

public class NotificationService implements  INotificationSubject{

    protected static final Logger logger = Logger.getLogger(NotificationService.class);
    private volatile static NotificationService uniqueFactory;
      private ArrayList observers;

    private NotificationService() {
      observers = new ArrayList();
    }
    public static NotificationService getInstance() {
        if (uniqueFactory == null) {
            synchronized (NotificationService.class) {
                if (uniqueFactory == null) {
                    uniqueFactory = new NotificationService();
                }
            }
        }
        return uniqueFactory;
    }

    public static INotification GetNotificationObject(DeviceTypes Types) {
        INotification messageSender = null;

        if (Types == Types.IOS) {
            messageSender = new IosNotification();
        }

        return messageSender;
    }

    public void registerObserver(INotificationObserver o) {
        observers.add(o);
    }

    public void removeObserver(INotificationObserver o) {
        int i =
                observers.indexOf(o);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    public void notifyObserver(PushedNotification notification) {
        for (int i = 0; i < observers.size(); i++) {
            INotificationObserver observer = (INotificationObserver) observers.get(i);
            observer.update(notification);
        }
    }

    public void messageSendInfo(PushedNotification notification) {
        notifyObserver(notification);
    }

    public void showSentInfo(PushedNotification notification) {
        messageSendInfo(notification);
    }
}
4

2 回答 2

2

你需要一个实例:

INotificationObserver ino = new PushTest();
ns.registerObserver(ino);

因此,您不需要该ns属性。

于 2013-03-15T12:47:06.973 回答
0

典型的解决方案是在 main 方法中初始化你的类:

public class PushTest implements INotificationObserver{
    NotificationService ns = NotificationService.getInstance();

    public static void main(String[] args) {         
        PushTest pushTest = new Pushtest();
        ...

等等等等

于 2013-03-15T12:47:03.127 回答