"Swizzle" (maybe Reflection?) AddView () On Android

I know you cannot Swizzle in Java.

I've been doing some research and I think "maybe" you can do Reflection in Java to do Swizzle like behavior (which you can do on iOS).

The culprit (and one of the worst design decisions I've ever seen) is the function addView()

on all Android ViewGroup objects. You have to explicitly check if the parent is null (sometimes you even need to cast the parent to get the behavior you want!). Gross.

I want to change the behavior of this (without creating a million subclasses) if the method addView()

does it automatically so that the client code can ignore it.

This is something I can do with Reflection (from what I understand it would require special calls at runtime, instead of actually changing the root method call [so maybe not good enough]) or something what else? Or am I barking the wrong tree?

+3


source to share


1 answer


As you mentioned, without creating a million subclasses (or better, one subclass for each class where you want to override the implementation addView

), this is not possible. This is really the correct way to do it, and also means you can use these subclasses in XML layout files.

Reflection will allow you to inspect classes / interfaces / fields / methods at runtime, but it will not allow you to change their already defined behavior provided by the underlying implementation that has been compiled. Although some changes are possible, such as access to private methods / fields.



Gray Area Options ...

One area to look out for will be the Mockito

one that allows you to spy around existing object instances, which will allow you to override the default. This is achieved with Java proxies and InvocationHandler

s
. However, at this point I will stop and say that your production code should not contain any test code, and Mockito is clearly designed to do so. Moreover, given that, at least in the past, it was difficult (if not impossible) to install proxy servers around some Android classes such as View

and Context

s. I believe this has been authorized by DexMakerand I have less knowledge about myself, but it allows you to generate runtime code. This will be a different direction to look at. I personally believe that none of these should be perceived as a possible solution worthy of production code, but something to play with for your own curiosity and learn from.

+3


source







All Articles