Annotation attribute must be a class literal? Why? Constants should be fine too

后端 未结 5 823
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-13 18:55

Can someone explain why String and Class annotation parameters are expected differently? Why does the compiler require literals for Classes, wherby accepting constants for Strin

5条回答
  •  被撕碎了的回忆
    2021-02-13 19:18

    Room doesn't have a native support for storing dates, you need to convert it to LONG values while inserting and reading to and from the database. Hence we are responsible to instruct the Room database on how to convert the data.

    For that, thanks to room architecture, we have TypeConverter class. Well, don't get carried away, there isn't a special class that you can just extend and get things done, but its something you have to write from scratch but it does use Annotations to make it work with Room.

    For example, while dealing with Dates :

    import android.arch.persistence.room.TypeConverter;
    import java.util.Date;
    
    //Type-Converter Class for Room
    public class DateConverter {
        @TypeConverter
        // Long value to Date value
        public static Date toDate(Long timestamp) {
            return timestamp == null ? null : new Date(timestamp);
        }
    
        @TypeConverter
        // Date value to Long value
        public static Long toTimestamp(Date date) {
            return date == null ? null : date.getTime();
        }
    }
    

    Now, we have to tell our Database class to use this TypeConverter Class using @TypeConverters (make sure to use plural version).

    @Database(entities = {Entity.class}, version = 1)
    @TypeConverters(DateConverter.class)
    public abstract class AppDatabase extends RoomDatabase {...}    
    

    You are ready to rock!

提交回复
热议问题