如何在Java中创建自定义事件

时间:2016-03-18 10:23:56

标签: java c# events

即使经过一段时间尝试阅读和理解已在此处发布的主题,我仍然对如何使用Java创建事件感到困惑。

假设我在C#中有这个类:

public class HighlightsObjectHandler {
    // Constants
    private const String
        JsonKeysHighlightsHolder = "Items",
        JsonKeysHighlightUrl = "Url",
        JsonKeysHighlightTranslationsHolder = "Traducoes",
        JsonKeysHighlightTranslationLanguage = "Idioma",
        JsonKeysHighlightTranslationText = "Titulo",
        JsonKeysHighlightTranslationImage = "Imagem";

    // Handlers
    public event EventHandler HighlightsJsonChanged;

    public event EventHandler HighlightsContentChanging;
    public event EventHandler HighlightsContentChanged;

    // Variables
    private String
        _json;

    // Properties
    public String HighlightsJson {
        get {
            return _json;
        }
        set {
            if (value != _json && value != null) {
                _json = value;

                OnHighlightsJsonChanged( EventArgs.Empty );

                ParseJson();
            }
        }
    }

    public Boolean HighlightsUpdating { get; private set; }
    public List<HighlightObject> Highlights { get; private set; }

    // Methods
    private void ParseJson() {
        JsonObject
            jsonObject;

        if (JsonObject.TryParse( HighlightsJson, out jsonObject )) {
            OnHighlightsContentChanging( EventArgs.Empty );

            // Json parsing and other stuff...
            // ... it shouldn't matter for this question.

            OnHighlightsContentChanged( EventArgs.Empty );
        }
    }

    // Events
    internal void OnHighlightsJsonChanged( EventArgs eventArgs ) {
        if (HighlightsJsonChanged != null) {
            HighlightsJsonChanged( this, eventArgs );
        }
    }

    internal void OnHighlightsContentChanging( EventArgs eventArgs ) {
        HighlightsUpdating = true;

        if (HighlightsContentChanging != null) {
            HighlightsContentChanging( this, eventArgs );
        }
    }
    internal void OnHighlightsContentChanged( EventArgs eventArgs ) {
        HighlightsUpdating = false;

        if (HighlightsContentChanged != null) {
            HighlightsContentChanged( this, eventArgs );
        }
    }

    // Constructors
    public HighlightsObjectHandler() {
        Highlights = new List<HighlightObject>();
    }
}

如何在Java中创建副本

我有点明白,我需要创建一个interface来保存我在此代码中拥有的3 EventHandlers。然后,我必须在课堂上实现interface。我们假设该类具有完全相同的名称,结果将是这样的:

    public class HighlightsObjectHandler implements SomeListener { ... }

但是,从我从教程和论坛中看到的,他们会直接触发HighlightsContentChanging而不是调用OnHighlightsContentChanging(我想设置变量的地方 - {{1} - 一个值,然后调用与事件关联的HighlightsUpdating

我有失去理智的地方。我怎么能做到这一点?在Windows Phone应用程序中,只要页面中包含此内容的页面将页面设置为加载,或者如果页面无法显示任何内容,该变量将帮助我。

更新

我已经设法创建了我能够或已经承认的代码。到目前为止,我将留下代码:

listeners

3 个答案:

答案 0 :(得分:1)

我没有“JsonObject”类型的等价物,但除此之外,我认为以下内容可能对您有用,使用您自己的自定义EventHandler功能接口,自定义EventArgs类和通用“事件”助手类:

import java.util.*;

public class HighlightsObjectHandler
{
    // Constants
    private static final String JsonKeysHighlightsHolder = "Items",
        JsonKeysHighlightUrl = "Url",
        JsonKeysHighlightTranslationsHolder = "Traducoes",
        JsonKeysHighlightTranslationLanguage = "Idioma",
        JsonKeysHighlightTranslationText = "Titulo",
        JsonKeysHighlightTranslationImage = "Imagem";

    // Handlers
    public Event<CustomEventHandler> HighlightsJsonChanged = new Event<CustomEventHandler>();

    public Event<CustomEventHandler> HighlightsContentChanging = new Event<CustomEventHandler>();
    public Event<CustomEventHandler> HighlightsContentChanged = new Event<CustomEventHandler>();

    // Variables
    private String _json;

    // Properties
    public final String getHighlightsJson()
    {
        return _json;
    }
    public final void setHighlightsJson(String value)
    {
        if (!_json.equals(value) && value != null)
        {
            _json = value;

            OnHighlightsJsonChanged(CustomEventArgs.Empty);

            ParseJson();
        }
    }

    private boolean HighlightsUpdating;
    public final boolean getHighlightsUpdating()
    {
        return HighlightsUpdating;
    }
    private void setHighlightsUpdating(boolean value)
    {
        HighlightsUpdating = value;
    }
    private ArrayList<HighlightObject> Highlights;
    public final ArrayList<HighlightObject> getHighlights()
    {
        return Highlights;
    }
    private void setHighlights(ArrayList<HighlightObject> value)
    {
        Highlights = value;
    }

    // Methods
    private void ParseJson()
    {
        //todo: no equivalent to 'JsonObject':
        JsonObject jsonObject = null;

        //todo: no equivalent to 'out' parameter:
        if (JsonObject.TryParse(HighlightsJson, jsonObject))
        {
            OnHighlightsContentChanging(CustomEventArgs.Empty);

            // Json parsing and other stuff...
            // ... it shouldn't matter for this question.

            OnHighlightsContentChanged(CustomEventArgs.Empty);
        }
    }

    // Events
    public final void OnHighlightsJsonChanged(CustomEventArgs eventArgs)
    {
        if (HighlightsJsonChanged != null)
        {
            for (CustomEventHandler listener : HighlightsJsonChanged.listeners())
            {
                listener.invoke(this, eventArgs);
            }
        }
    }

    public final void OnHighlightsContentChanging(CustomEventArgs eventArgs)
    {
        setHighlightsUpdating(true);

        if (HighlightsContentChanging != null)
        {
            for (CustomEventHandler listener : HighlightsContentChanging.listeners())
            {
                listener.invoke(this, eventArgs);
            }
        }
    }
    public final void OnHighlightsContentChanged(CustomEventArgs eventArgs)
    {
        setHighlightsUpdating(false);

        if (HighlightsContentChanged != null)
        {
            for (CustomEventHandler listener : HighlightsContentChanged.listeners())
            {
                listener.invoke(this, eventArgs);
            }
        }
    }

    // Constructors
    public HighlightsObjectHandler()
    {
        setHighlights(new ArrayList<HighlightObject>());
    }
}

@FunctionalInterface
public interface CustomEventHandler
{
    void invoke(object sender, CustomEventArgs e);
}
public class CustomEventArgs
{
    public static readonly CustomEventArgs Empty;

    public CustomEventArgs()
    {
    }
}

//this is produced as a helper class by C# to Java Converter:
public final class Event<T>
{
    private java.util.Map<String, T> namedListeners = new java.util.HashMap<String, T>();
    public void addListener(String methodName, T namedEventHandlerMethod)
    {
        if (!namedListeners.containsKey(methodName))
            namedListeners.put(methodName, namedEventHandlerMethod);
    }
    public void removeListener(String methodName)
    {
        if (namedListeners.containsKey(methodName))
            namedListeners.remove(methodName);
    }

    private java.util.List<T> anonymousListeners = new java.util.ArrayList<T>();
    public void addListener(T unnamedEventHandlerMethod)
    {
        anonymousListeners.add(unnamedEventHandlerMethod);
    }

    public java.util.List<T> listeners()
    {
        java.util.List<T> allListeners = new java.util.ArrayList<T>();
        allListeners.addAll(namedListeners.values());
        allListeners.addAll(anonymousListeners);
        return allListeners;
    }
}

答案 1 :(得分:0)

import java.util。*; 接口HelloListener {void someoneSaidHello();}

答案 2 :(得分:0)

我将以StackOverflow answer作为我在此答案中解释的基础。

好吧,那么,对于我能阅读和理解的内容,在Java中构建类似C#的事件并不是那么多(或者,从另一个角度来看,它并不是那么难谁用C#开发用Java构建事件。

首先,从我的角度来看,我想指出我在Java中构建事件的方式几乎是来自C#的复制粘贴(也许它是正确的方法,也许它不是。

其次,我会 - 希望 - 以人们可能理解的方式(基于我在StackOverflow和其他网站上看到的教程)这样做:

  • C#上的事件包含在一个设置为internal的方法中 - 通常是OnSomethingChangingOnSomethingChanged - 而Java事件则不是。想象一下Java中的这个方法:

    List<HelloListener> listeners = new ArrayList<HelloListener>();
    
    public void sayHello() {
        System.out.println("Hello!!");
    
        // Notify everybody that may be interested.
        for (HelloListener hl : listeners)
            hl.someoneSaidHello();
    }
    

    现在,为了使它更像C#,我会这样做:

    public event EventHandler HelloListener;
    
    public void SayHello() {
        Console.WriteLine("Hello!!");
    
        // Notify everybody that may be interested.
        if(HelloListener != null) {
            HelloListener(this, EventArgs.Empty);
        }
    }
    

    基本上我期望必须创建一个OnHelloListener方法,然后在那个方法上触发事件,但是,在我看到的大多数示例和教程中,他们会像我上面写的那样做。这真是让我的头脑变得非常糟糕(如果他们从C#变成Java,也可能是其他人)。

总结

如果我将<{em>} 从C#转换为 - 并且将C#soul 保留在其中 - 我会以这样的结尾:

HighlightsObjectHandler

再次,我的问题基本上是我期望必须创建会触发事件的public class HighlightsObjectHandler { // Constants private final String JsonKeysHighlightsHolder = "Items", JsonKeysHighlightUrl = "Url", JsonKeysHighlightTranslationsHolder = "Traducoes", JsonKeysHighlightTranslationLanguage = "Idioma", JsonKeysHighlightTranslationText = "Titulo", JsonKeysHighlightTranslationImage = "Imagem"; // Enumerators // Handlers private List<HighlightsListener> _highlightsListeners = new ArrayList<HighlightsListener>(); // Variables private String _json; private Boolean _updating; private List<HighlightObject> _highlights; // Properties public String HighlightsJson() { return _json; } public void HighlightsJson(String highlightsJson) { // Validate the json. This cannot be null nor equal to the present one ( to prevent firing events on the same data ) if (!highlightsJson.equals(_json) && highlightsJson != null) { _json = highlightsJson; OnHighlightsJsonChanged(); ParseJson(); } } public Boolean HighlightsUpdating() { return _updating; } private void HighlightsUpdating(Boolean isUpdating) { _updating = isUpdating; } public List<HighlightObject> Highlights() { return _highlights; } // Methods private void ParseJson() { if (HighlightsUpdating()) { return; } try { OnHighlightsContentsChanging(); // Parse the JSON object OnHighlightsContentsChanged(); } catch (JSONException exception) { } } // Events private void OnHighlightsJsonChanged() { for(HighlightsListener highlightsListener : _highlightsListeners) { highlightsListener.HighlightsJsonChanged(); } } private void OnHighlightsContentsChanging() { HighlightsUpdating(true); for(HighlightsListener highlightsListener : _highlightsListeners) { highlightsListener.HighlightsContentChanging(); } } private void OnHighlightsContentsChanged() { HighlightsUpdating(false); for(HighlightsListener highlightsListener : _highlightsListeners) { highlightsListener.HighlightsContentChanged(); } } // Constructors public HighlightsObjectHandler() { _highlights = new List<HighlightObject>(); } } 方法,而不是当我希望它们被触发时直接放在方法上的代码。

您可以说我是一个应用程序,当您在键入OnSomethingChanged时键入this时崩溃了。

Java to C#

警告如果您很容易混淆或者您仍在尝试理解这一点,我建议您不要阅读这部分答案。这只是一个有趣和好奇块的,我发现它有点有趣和有趣......

所以,让我们说我的问题与现在相反,我有一个带有事件的Java类,并希望转换为C#。从我所知到的这一点来看,我会在C#中以这样的结尾结束:

that

请注意如何删除public class HighlightsObjectHandler { // Constants private const String JsonKeysHighlightsHolder = "Items", JsonKeysHighlightUrl = "Url", JsonKeysHighlightTranslationsHolder = "Traducoes", JsonKeysHighlightTranslationLanguage = "Idioma", JsonKeysHighlightTranslationText = "Titulo", JsonKeysHighlightTranslationImage = "Imagem"; // Enumerators // Handlers public event EventHandler HighlightsJsonChanged; public event EventHandler HighlightsContentChanging; public event EventHandler HighlightsContentChanged; // Variables private String _json; // Properties public String HighlightsJson { get { return _json; } set { if (value != _json && value != null) { _json = value; if (HighlightsJsonChanged != null) { HighlightsJsonChanged( this, eventArgs ); } ParseJson(); } } } public Boolean HighlightsUpdating { get; private set; } public List<HighlightObject> Highlights { get; private set; } // Methods private void ParseJson() { JsonObject jsonObject; if (JsonObject.TryParse( HighlightsJson, out jsonObject )) { HighlightsUpdating = true; if (HighlightsContentChanging != null) { HighlightsContentChanging( this, eventArgs ); } // Json parsing HighlightsUpdating = false; if (HighlightsContentChanged != null) { HighlightsContentChanged( this, eventArgs ); } } } // Events // Constructors public HighlightsObjectHandler() { Highlights = new List<HighlightObject>(); } } 和其他OnHighlightsJsonChanged方法,而不是使用方法代码而不是我调用方法的代码。

PS: 我会在下周一将此答案标记为此问题的答案,以便我可以看到其他人的答案并选择其中一个,如果他们更合适作为最终答案。