Reputation: 5537
Is the a way the cast below can be avoided?
//Is there a way this can be implemented so the cast is not necessary?
FooService fooService = new FooService();
Foo f = (Foo)fooService.findById(id);
public class FooService extends DomainServiceImpl<Foo> {
}
public class DomainService<T extends Persistable>{
private Class<T> type;
public void findById(long id) {
domainDao.findById(id, type);
}
}
edit: Still have to cast
public T findById(long id) {
return (T) fooDao.findById(id, type);
}
Upvotes: 0
Views: 2097
Reputation: 38132
You can use:
type.cast(object);
to avoid the warning.
Note that this still might throw a ClassCastException.
If you're not sure that the object can be cast, check with:
if (type.isInstance(object)){
return type.cast(object);
} else {
...
}
Upvotes: 0
Reputation: 3592
Hmm, before this gets a tree of comments I will post a solution which might fit your needs. You'll have to adapt it to your specific problem however.
The main idea is, that the method findById
is returning the generic type T
so you do not need the type cast in your code.
class Solution {
static class Foo extends Persistable {
}
public static void main(String[] args) {
FooService fooService = new FooService();
Foo f = fooService.findById(0l);
}
static class FooService extends DomainService<Foo> {
FooService() {
type = Foo.class;
}
}
static class Persistable {
}
static class DomainService<T extends Persistable> {
Class<T> type;
public T findById(long id) {
try {
return this.type.newInstance();
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
Upvotes: 1