Java泛型防止由于访问通用静态字段而导致的类型不匹配错误

时间:2015-07-26 05:06:57

标签: java generics

我有这三个类:

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#000000"
        android:textColor="#ffffff"
        android:text="Button" />

我遇到的问题是由于错误,我无法访问方法hasNote()中的hashMap:

public class EntityType<T extends Entity> implements Serializable {

    public String mRelationType;
    public Class<T> mClass;
    public int mTypeId;
    public int mTypeTitleId;

    public EntityType(final int typeId, final Class<T> entityClass, final String relationType, final int typeTitleId) {
        this.mTypeId = typeId;
        this.mClass = entityClass;
        this.mRelationType = relationType;
        this.mTypeTitleId = typeTitleId;
    }
    ...
}

public class MyApplication extends Application {
    ...
    public static HashMap<Integer, EntityType<? extends Entity<?>>> entityTypes;
    ...
}

public abstract class Entity<T extends Entity<T>> {

    public static <T extends Entity<T>> List<T> getAll(final EntityType<T> type) {
        return getDao(type.mClass).queryForAll();
    }

    public static <T extends Entity<T>> List<T> getAllOrphans(final EntityType<T> type) {
        try {
            return getDao(type.mClass).queryBuilder().where().isNull(Column.PARENT).query();
        }catch(SQLException e){
            return new ArrayList<>();
        }
    }

    public static <T extends Entity> T getById(final EntityType<T> type, final int id) {
        return getDao(type.mClass).queryForId(id);
    }


    //TODO: Fix warnings
    public void save() {
        getDao(getEntityType().mClass).createOrUpdate((T) this);
    }


    public void remove() {
        getDao(getEntityType().mClass).delete((T) this);
    }

    public static <T extends Entity> RuntimeExceptionDao<T, Integer> getDao(Class<T> entityClass) {
        return MyApplication.getDBHelper().getRuntimeExceptionDao(entityClass);
    }

    public T getSingle(List<T> entities) {
        return !entities.isEmpty() ? entities.get(0) : null;
    }

    public List<T> getRelated(final EntityType<T> type){
        return MyQuery.getAllRelated(getEntityType(), getId(), type);
    }

    public boolean hasNote(){
        return !getRelated(MyApplication.entityTypes.get(NoteEntity.TYPE)).isEmpty();
    }
    public abstract EntityTypeClass<T> getEntityTypeClass();
    ...
}

但是,如果我将hashmap的签名更改为HashMap,它将进行编译,但是会给我一个警告&#34;未经检查的赋值&#34;。但我想尽可能多地忽视警告。

0 个答案:

没有答案