lundi 8 février 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).

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;

    }





Aucun commentaire:

Enregistrer un commentaire