views:

72

answers:

3

Hi. I'm kind of lame with generics, but I wonder, for the following class:

static class SomeClass<T> {
 private T value;

 public SomeClass(T value) {
  T.class?
  this.value = value;
 }

 public T getValue() {
  return value;
 }
}

If called for example: SomeClass<String> stringer = new SomeClass<String>("Hello"); Is it possible to get String.class (or whatever T would be) in the constructor?

Ok, wait a sec, I'm going to explain what I'm trying to solve

The actual problem is that I'm using OrmLite and I have a lot of DAO objects, like this one:

public class PostDAO extends BaseJdbcDao<Post, String> {
    public PostDAO(DatabaseType databaseType) {
        super(databaseType, Post.class);
    }
}

For Domain it is:

public class DomainDAO extends BaseJdbcDao<Domain, String> {
 public DomainDAO(DatabaseType databaseType) {
  super(databaseType, Domain.class);
 }
}

and so on. I wanted to parametrize these, so that I can only have one:

public class DAO<K, V> extends BaseJdbcDao<K, V> {
 public DAO(DatabaseType databaseType) {
  super(databaseType, (WHAT HERE?));
 }
}

but I'm stuck on the what here part)

A: 

value.getClass() should do the trick (assuming value is never null!)

ammoQ
what if I don't have value?
htf
Then you can't. This information is only available at compile time. At runtime there is just `Object`.
musiKk
I think that BaseJdbcDao has the class argument as parameter because you can not get the class from the type parameter.As Dao is not a concrete class itself, you can add the class parameter there too.
tkr
+1  A: 

What about:

public class DAO<K, V> extends BaseJdbcDao<K, V> {
 public DAO(DatabaseType databaseType, Class databaseClass) {
  super(databaseType, databaseClass);
 }
}
pakore
A: 

pakore's answer is a good one but I wanted to add that you don't have to define the per-class DAO object. I recommended it in the ORMLite documentation but it's supposed to be a convenience, not a pain.

You can always do something like the following using BaseJdbcDao as an anonymous class:

BaseJdbcDao<Post, String> postDao =
    new BaseJdbcDao<Post, String>(databaseType, Post.class) {
    };
postDao.setDataSource(dataSource);
postDao.initialize();

I do that a lot in the ORMLite junit tests. Might be better to have a utility method like the following. I've just added it to the BaseJdbcDao class which will be in the 2.7 release.

public static <T, ID> Dao<T, ID> createDao(DatabaseType databaseType,
    DataSource dataSource, Class<T> clazz) throws SQLException {
    BaseJdbcDao<T, ID> dao = new BaseJdbcDao<T, ID>(databaseType, clazz) {
    };
    dao.setDataSource(dataSource);
    dao.initialize();
    return dao;
}
Gray