4

我知道您实际上不能在 Java 中进行 Swizzle。

我正在做一些研究,我认为“也许”你可以在 Java 中做反射来完成类似 Swizzle 的行为(你可以在 iOS 上做)。

罪魁祸首(也是我见过的最糟糕的设计决策之一)是addView()所有 Android ViewGroup 对象上的函数。您必须明确检查父级是否为空(有时甚至需要强制转换父级以获得所需的行为!)。总的。

addView()我想通过让该方法自动执行此检查来更改此行为(不创建一百万个子类),以便客户端代码可以忽略它。

这是我可以用反射做的事情吗(据我所知,它需要特殊的运行时调用,而不是实际更改根方法调用[所以可能不够好]),还是其他什么?还是我在叫错树?

4

1 回答 1

3

As you mentioned, without creating a million subclasses (or better put, one subclass for every class where you would like to override the addView implementation) this doesn't seem possible. This would actually be the right way to do it, and it also means that you can use these subclasses in XML layout files.

Reflection would allow you to inspect classes/interfaces/fields/methods at runtime, but it won't allow you to change their already defined behaviour provided by the underlying implementation which has been compiled. Although some changes are possible, such as making private methods/fields accessible.

Grey-area options incoming...

One direction worth looking into would be Mockito, which allows you to create spies around existing object instances that would allow you to override the default implementation. This is achieved through Java's proxies and InvocationHandlers. However, at this point I'll stop and say that your production code should not contain any test code and Mockito is clearly meant for that. More so considering that, at least in the past, it used to be hard (if not impossible) to put proxies around some of Android's classes such as Views and Contexts. I believe this has been resolved by DexMaker, which I have less knowledge of myself but it does allow you to perform runtime code generation. This would be another direction worth looking at. I personally think that neither of these should be taken as possible solutions worthy of production code, but something to have a play with for your own curiosity and to learn from.

于 2015-07-17T19:14:31.053 回答