Reputation: 3
I have a class named "toto" which I send to a function that does the following:
getData(toto);
public String getData(Class myClass) {
javax.jdo.Query query = p.newQuery(myClass);
List<myClass> list = (List<myClass>) pm.newQuery(query).execute();
for (myClass element : list) {
Do something here
}
}
The problem is that I get type compilation error. What am I doing wrong?
Joel
Upvotes: 0
Views: 57
Reputation: 597076
You can achieve that the following way:
public <T> String getData(Class<T> myClass) {
javax.jdo.Query query = p.newQuery(myClass);
List<T> list = (List<T>) pm.newQuery(query).execute();
for (T element : list) {
Do something here
}
}
where, if you want to call any method other than toString()
on element
, you will need an interface/base type and change the definition to <T extends YourInterface>
Upvotes: 1
Reputation: 413720
You can't use a runtime variable as an "argument" to a generics construct (like List<X>
). If you know something about the classes you'll pass in, then you can constrain that:
public String getData(Class<? extends Something> myClass) {
// ...
List<Something> list = (List<Something>) // ...
Upvotes: 2