I’m new to java so apologies if I’ve got totally the wrong end of the stick.
I’m trying to write a generic (in the English sense of the word!) Data Access class.
eg I currently have:
public class DA<T> {
public static Dao getAccountDao() throws NamingException, SQLException {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/test");
ConnectionSource connectionSource = new DataSourceConnectionSource(dataSource, new MysqlDatabaseType());
Dao<Account, Integer> accountDao = DaoManager.createDao(connectionSource, Account.class);
return accountDao;
}
}
And I can call this with:
Dao<Account, Integer> accountDao = DA.getAccountDao();
But I’ll need a version of this for every Dao/model. So I’m trying to make something that can be called like:
Dao<SomeClass, Integer> someClassDao = DA.getDao(SomeClass);
Is this even possible?
I’ve tried things like:
public class DA {
public static Dao getDao(<T>) throws NamingException, SQLException {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/test");
ConnectionSource connectionSource = new DataSourceConnectionSource(dataSource, new MysqlDatabaseType());
Dao<T, Integer> accountDao = DaoManager.createDao(connectionSource, T.class);
return accountDao;
}
}
but Netbeans gives the error: illegal start of type
My brain is struggling with generics, is this something they can do?!
EDIT: With help from the posts below I’ve got to:
public class DA<T> {
public static Dao<T, Integer> getDao(T daoType) throws NamingException, SQLException {
Dao<T, Integer> accountDao = DaoManager.createDao(T.class);
return accountDao;
}
}
Which generates two errors:
non-static type variable T cannot be referenced from a static context
and if I remove the static keyword, I get:
cannot select from a type variable
I need to read up on how generics and static work together, but the 2nd looks like a consequence of erasure (http://www.coderanch.com/t/386358/java/java/Converting-type-parameters-class) , so not sure if it’s going to be possible.
Should have mentioned earlier, the Dao stuff is using an ORM library called ORMLite, so createDao etc isn’t my code.
To access what you mean by
T.class, you’ll have to pass the class object into the method: