How can i create an instance of the given generic type class with a subtype Class<Foo<Bar>> type = ??
Its easy for simple generic such as: Class<Foo> type = Foo.class; but how to do this here?
final Class<Foo<Bar>> type = null; // ??? We cannot do something like Foo<Bar>.class which is possible in c# as far as i know.
I want to use this type in a generic function which works for all simple generics but not if nested.
Foo<Bar> fooBar = getRecord(type, 1); static T get(Class<T> type, int id) { // load from database return session.get(type, id); } Complex example
The production example is more complex having a DAO class with many methods that rely on the generic type.
interface Entity {} class Foo<T extends Entity> extends Entity {} class Bar extends Entity {} class EntityDAO<T extends Entity> { Class<T> type; Session session; public EntityDAO(Class<T> type) { this.type = type; } public T get(int id) { return session.get(type, id); } } public class TestSession { public <T> T get(final Class<T> type, final int id) { Objects.requireNonNull(type); return null; } }
void static main(String[] args) { final Class<Foo<Bar>> type = null; // how to set type here? EntityDAO<Foo<Bar>> fooBarDAO = new EntityDAO<>(type); Foo<Bar> entity = fooBarDAO.get(1); } Currently i am just using the main type Foo.class loosing the Bar.class information for the DAO.
TypeToken<Foo<Bar>>), or you'll need to send the generic paremeter as well e.g.getRecord(Foo.class, Bar.class, 1);. This is a limitation of java's generics. If you can provide a more concrete example, there may be alternative solutions.(Class<Foo<Bar>>) foo.getClass();. But note that depending on how you want to implement this, it might not be any use in your case.TypeTokenis a nice example, which will need some factoring but will consider this. I edited the question with a second more complex example.TypeTokendoes not work cause in myEntityDAOi still pass the type as an argument to the constructor so the token just delegates the problem. The moment i need the class as a "variable" i am stuck.<Bar>information is lost but it does not matter cause i only need the mainFooentity to access database entity table. Just for cleaner code i needFoo<Bar>. A alternate solution is to add constructorpublic <V extends T> EntityDAO(Class<V> type)and do casting inside and just passFoo.class. I removed my comments.