This article introduces the method of using Anntation instead of ENUM in Android. I will share it with you. The details are as follows:
How to replace
As we all know, ENUM in java is not recommended for programming in Android development. Because each value in ENUM will be an Object object. Compared with constant int and String, it consumes much more memory.
So, how do we limit user input when defining some constants? For example:
If ENUM is used, we generally define four seasons of the year as follows:
public enum Season { SPRING, SUMMER, FALL, WINTER }
Use custom constants instead:
public class ConstantSeason { public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3; public static final int WINTER = 4; }
However, there is a problem with this method of using constants, such as the following method
public void setSeason(int season)
How do you ensure that the value passed in by the user when using this method is one of, , ,?
Android provides us with annotation prompt method in the Annotation package, and the usage is as follows:
public class Season { public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3; public static final int WINTER = 4; @IntDef({WINTER, SPRING, SUMMER, FALL}) @Retention() public @interface Season { } public void setSeason(@Season int season){ ("season" + season); } }
When the user calls the setSeason method, the value passed in is not one of WINTER, SPRING, SUMMER, and FALL.
AndroidStudio will prompt an error.
This can remind developers of the values here, and there is a problem with the incoming.
in conclusion
Enumerate bytes that increase at least twice the size of the general APK than the normal amount, and can use 5 to 10 times more RAM memory than the equivalent constant. In order to optimize the performance of apk, it is recommended to use Anntation instead of ENUM.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.