Hi,
I just start developping on android and i'm missing the EventHandler from c#. As a learning process, I started to write an EventHandler in java. It's almost good execept the method:
getSlider_WantedValueChangedMethod()
I need to get it through reflection, and the name is a String. So when you refactor, It will not change.
What do you think about it? Is there a better way?
Manu
EventHandler.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Vector;
public class EventHandler<T extends EventArgs> {
Vector<EventHandlerItem> subscribers = new Vector<EventHandlerItem>();
public void Invoke(Object sender,T eventArgs) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
for (int i = 0, size = subscribers.size(); i < size; i++)
{
EventHandlerItem item = subscribers.get(i);
item.Method.invoke(item.Subscriber,sender, eventArgs);
}
}
public void add(Object subscriber,Method method) {
subscribers.add(new EventHandlerItem(subscriber,method));
}
public void remove(Object subscriber) {
subscribers.remove(subscriber);
}
}
EventArgs
import java.util.EventObject;
public class EventArgs extends EventObject{
private static final long serialVersionUID = 9202854783245818504L;
public EventArgs(Object source) {
super(source);
}
}
EventArgs1
public class EventArgs1<T> extends EventArgs{
private static final long serialVersionUID = -1694366721997799870L;
private T property;
public T getProp()
{
return property;
}
public EventArgs1(Object source,T property) {
super(source);
this.property = property;
}
}
EventHandlerItem
import java.lang.reflect.Method;
final class EventHandlerItem {
public Object Subscriber;
public Method Method;
public EventHandlerItem(Object subscriber,Method method)
{
this.Subscriber =subscriber;
this.Method = method;
}
}
slider
public EventHandler<EventArgs1<Double>> onWantedValueChanged = new EventHandler<EventArgs1<Double>>();
private void InvokeWantedValueChanged(double value) throws Exception
{
onWantedValueChanged.Invoke(this,new EventArgs1<Double>(this,value));
}
public double getWantedValue()
{
return wantedValuePercent;
}
public void setWantedValue(double value)
{
if (wantedValuePercent == value) return;
wantedValuePercent = value;
try {
InvokeWantedValueChanged(value);
}
catch (Exception ex){}
}
Implementation
slider.onWantedValueChanged.add(this,getSlider_WantedValueChangedMethod());
private static Method slider_WantedValueChangedMethod;
public Method getSlider_WantedValueChangedMethod() {
if (slider_WantedValueChangedMethod != null)
return slider_WantedValueChangedMethod;
try {
slider_WantedValueChangedMethod = getClass().getDeclaredMethod(
"slider_WantedValueChanged",Object.class, EventArgs1.class);
} catch (Exception e) {
}
return slider_WantedValueChangedMethod;
}
public void slider_WantedValueChanged(Object sender,EventArgs1<Double> wantedValue)
{
}