sverin February 2016

Understanding generics and reflection

I need some help with generics and reflection in java.

What I try to achieve is a factory class that based on a class MyClass returns another class MyClassStore that implements an interface Store<MyClass>.

How can I make sure that the right type of store is returned with reflection.

See sample code:

public class Application {

    public static void main(String[] args) {

        Store<MyClass> store = Factory.getFactory(MyClass.class);
        MyClass myClass = store.get();
        System.out.println(myClass.getId());

    }

}

public class Factory {

    public static <T> Store<T> getFactory(Class<T> type) {

        Store<T> store = null;
        // TODO: How to implement this
        return store;

    }

}

public class MyClassStore implements Store<MyClass>{

    public MyClass get() {
        return new MyClass("1000");
    }

}

public interface Store<T> {

    public T get();

}

public class MyClass {

    private String id;

    public MyClass(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

I have tried different ways but can't get it to work the way I want. This is the implementation I have tried. But is there a better way?

    public static <T> Store<T> getFactory(Class<T> type) {

        Store<T> store = null;

        if (type == MyClass.class) {
            store = (Store<T>) new MyClassStore();
        }

        return store;

    }

Answers


Douglas February 2016

Just taking the problem as stated, the best solution I can come up with is to have a static final Map<Class, Class> in the Factory that maps (in this example) from MyClass.class to MyClassStore.class, use it to look up which class to instantiate, and call newInstance() on the Class retrieved from the map.

Taking a bit more liberty with your design, you could replace MyClassStore with a more general generic class that takes a Class<T> parameter, stores it locally, and implements get() with a call to newInstance() on the stored Class. getFactory() could then simply make a generic store regardless and pass the Class object on.

However, this type of code strikes me as unlikely to be a good solution to whatever your real problem is. Why does MyClassStore need to create new MyClass objects? Why does the internal logic of any implementation of Store need to care about what type T actually is? That latter question in particular is usually a strong indicator of poor design in my opinion.

Post Status

Asked in February 2016
Viewed 1,792 times
Voted 13
Answered 1 times

Search




Leave an answer