Created
December 2, 2013 12:41
-
-
Save alexoro/7748909 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Target(ElementType.METHOD) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Property { | |
String[] property() default {}; | |
} | |
public class PropertyChangeListenerAnnotated implements PropertyChangeListener { | |
private Handler mDefaultHandler; | |
public PropertyChangeListenerAnnotated() { | |
this(null); | |
} | |
public PropertyChangeListenerAnnotated(Handler defaultHandler) { | |
mDefaultHandler = defaultHandler; | |
} | |
@Override | |
public void propertyChange(final PropertyChangeEvent propertyChangeEvent) { | |
for (Method method: getClass().getMethods()) { | |
for (Annotation annotation: method.getAnnotations()) { | |
if (annotation instanceof Property) { | |
Property propertyAnnotation = (Property) annotation; | |
for (String property: propertyAnnotation.property()) { | |
if (property.equals(propertyChangeEvent.getPropertyName())) { | |
invoke(method, propertyChangeEvent); | |
} | |
} | |
} | |
} | |
} | |
} | |
protected void invoke(final Method method, final PropertyChangeEvent propertyChangeEvent) { | |
final Object self = this; | |
if (mDefaultHandler != null) { | |
mDefaultHandler.post(new Runnable() { | |
@Override | |
public void run() { | |
try { | |
method.invoke(self, propertyChangeEvent.getOldValue(), propertyChangeEvent.getNewValue()); | |
} catch (Exception ex) { | |
throw new RuntimeException(ex); | |
} | |
} | |
}); | |
} else { | |
try { | |
method.invoke(self, propertyChangeEvent.getOldValue(), propertyChangeEvent.getNewValue()); | |
} catch (Exception ex) { | |
throw new RuntimeException(ex); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment