
如果已经敲了几年代码,这样写会不会显得太Low
以下提供几种改良办法:
一、首先提到反射:
反射不太好,性能开销大,官方文档说过的。不是迫不得已不用反射,直接略过。附上副作用的官方文档:“Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
Performance OverheadBecause reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.Security RestrictionsReflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.Exposure of InternalsSince reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.“
二、中国特色法:(逗比法,仅限逗比参考,慎用)
介绍一种我在知乎上搜到的野路子,绝壁是跨界运用大神,直接上图:

三、说说,我是怎么用的
方法一:(推荐使用)

定义一个f(int id)方法:
private T f(int viewId) {
return (T) findViewById(viewId);
}
//可以直接写成
方法二:快捷键(可阅读性最好)
fbc+Tab
①局部变量时候.var

②全局变量时候.field

按下Enter后选择第二个

此时命名控件

另外Toast常用快捷键

按下Enter键,输入吐司内容即可

本文探讨了在编程中过度使用反射的弊端,包括性能开销、安全限制和内部暴露等问题,并提供了替代方案。作者分享了一种中国特色的编码方式,以及个人实践的两种快速编码方法,强调提高代码可读性和效率的重要性。
438

被折叠的 条评论
为什么被折叠?



