Android uses reflection to create a omnipotent SharedPreferences and androidpreferences that can store any object
We usually use SharedPreferences to store some data that needs to be stored locally but not stored in the database. Generally, it is very convenient to use it to store user names, passwords, and other data, if we want to store more than 10 pieces of information, we have to write more than 10 lines of repeated code to store them, you have to write more than 10 lines of code to get them one by one. Is there any way to store them in just one line of code, A line of code will take them out? The answer is yes. This article describes how to implement reflection.
1.Encapsulate the data we want to save into an object class Person. java. The attributes are modified using Public.
2.Through reflection, we can retrieve the attributes in the Person class. First, we can test whether the attributes have been obtained. add the following code in java for testing. Let's take a look at the Log printed information. We can see that all attributes in Person have been obtained.
3.Store objects in SharedPreferences
4.Get the object from SharedPreferences
5.Let's test and modify the code in mainacit.pdf. java. Let's take a look at the savedPerson information printed in the Log.
Source code download
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.