Skip to content

Instantly share code, notes, and snippets.

@alexoro
Created December 2, 2013 12:41
Show Gist options
  • Save alexoro/7748909 to your computer and use it in GitHub Desktop.
Save alexoro/7748909 to your computer and use it in GitHub Desktop.
@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