I am new to java, so I apologize if I have a completely wrong stick end.
I am trying to write a general (in the English sense of the word!) Data access class. For example, I 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 it with:
Dao<Account, Integer> accountDao = DA.getAccountDao();
But I will need a version of this for each Dao / model. Therefore, I am trying to do something that can be called the following:
Dao<SomeClass, Integer> someClassDao = DA.getDao(SomeClass);
Is it possible?
I 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 an error: illegal start of type
My brain is struggling with generics, is that what they can do ?!
EDIT: using the messages below I should:
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 I get: cannot select from a type variable I need to read about how common and static works together, but the second one looks like a result of erasing (http://www.coderanch.com/t/386358/java/java/Converting-type-parameters-class), so I'm not sure if this will be possible.
Should be mentioned earlier, Dao stuff uses an ORM library called ORMLite, so createDao, etc. is not my code.