Question

I am using db4o lib for storing data.

for example I have this code for storing data (i.e News)

public static void insertNewsToDB(Context context, final News news){
        final String dbPath = context.getDir("news", Context.MODE_PRIVATE) + "/"  + DB4O_NAME;
        ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), dbPath);
        try {
            db.store(news);
            db.commit();
        } finally {
            db.close();
        }
    }

and this getting data from db:

public static List<News> getNewsListFromDB(Context context){
        final List<News> news = new ArrayList<News>();
        final String dbPath = context.getDir("news", Context.MODE_PRIVATE) + "/"  + DB4O_NAME;
        ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), dbPath);
        try {
            ObjectSet<News> result = db.queryByExample(News.class);
            news.addAll(result);
        } finally {
            db.close();
        }

        return news;
    }

How could I create method so it's not depend on what type of class I have to pass. More clearly it doesn't depend on second parameter is News,User or something else. And same when I want get news from db.

I read about generics and cast objects but still I don't figure out how to this.

Please help.

Was it helpful?

Solution

Generics Example.

public class GenericsType<T> {

    private T t;

    public T get(){
        return this.t;
    }

    public void set(T t1){
        this.t=t1;
    }

    public static void main(String args[]){
        GenericsType<String> type = new GenericsType<>();
        type.set("Pankaj"); //valid

        GenericsType type1 = new GenericsType(); //raw type
        type1.set("Pankaj"); //valid
        type1.set(10); //valid and autoboxing support
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top