jeudi 5 mai 2016

How to make this method generic for all passed Class types?

I would like to make this method generic for all class types:

public static void printListSample(List<Class<?>> dateExtend) {
    System.out.println("dateExtend size: "+dateExtend.size());
    if(dateExtend.size() > 0){
        for(Class<?> mp : dateExtend){
            System.out.print("\n print entry - ");
            if(mp.getDate() != null){
                String dateDb = new SimpleDateFormat("dd.MM.yyyy.").format(mp.getDate());
                System.out.print("value: "+dateDb);
            }
        }
    }
    System.out.println();
}

Notice Class< ? > - now like this it doesen't work; but I think I am on the right track.

I would like to dinamically cast Class passed in the parameter and then dinamically cast it for for-loop (so I don't have to do if (instance of SomeClass.. )

How to do this? I would need example code, really don't know how to write this.

Edit: I would like to write generic method for printing List (or ArrayList) of any passed type:

<MyClass> or <String> or <SomeOtherClass>, 

so I wouldn't have to worry about types and casting would be done automatically.





Aucun commentaire:

Enregistrer un commentaire