tags:

views:

30

answers:

2

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

+2  A: 

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>) // ...
Pointy
Thanks!!! Very useful!
Joel
+1  A: 

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>

Bozho