Android uses reflection to create a omnipotent SharedPreferences and androidpreferences that can store any object

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.