I write service that interacts with other apps. It registers listeners on views (buttons, textviews,...), that already have listeners. I need to replace them with my own lis
public abstract class ReflectionUtils {
private static final String listenerInfoFieldName = "mListenerInfo";
private static final String onCLickListenerFieldName = "mOnClickListener";
public static OnClickListener getOnClickListener(View view){
Object listenerInfo = ReflectionUtils.getValueFromObject(view, listenerInfoFieldName, Object.class);
return ReflectionUtils.getValueFromObject(listenerInfo, onCLickListenerFieldName, View.OnClickListener.class);
}
public static T getValueFromObject(Object object, String fieldName, Class returnClazz){
return getValueFromObject(object, object.getClass(), fieldName, returnClazz);
}
private static T getValueFromObject(Object object, Class> declaredFieldClass, String fieldName, Class returnClazz){
try {
Field field = declaredFieldClass.getDeclaredField(fieldName);
field.setAccessible(true);
Object value = field.get(object);
return returnClazz.cast(value);
} catch (NoSuchFieldException e) {
Class> superClass = declaredFieldClass.getSuperclass();
if(superClass != null){
return getValueFromObject(object, superClass, fieldName, returnClazz);
}
} catch (IllegalAccessException e) {
}
return null;
}
}
Calling OnClickListener onClickListener = ReflectionUtils.getOnClickListener(myView);
on myView
will give you the myView
's listener that you are looking for.