0

I am Trying to write a generic method which accepts any type to List of Objects and then it checks for the type and downcast as per the type:

public Response generate(List<Object> objects){

    if(objects instanceof List<ClassA>){
        /*List<ClassA> classA =(List<ClassA>) (Object) objects;
        System.out.println(classA.lastIndexOf(classA));
        System.out.println("after downcasting");
*/      
        /*List<ClassA> customer = (List<ClassA>) objects.stream()
                .filter(ClassA.class::isInstance)
                .map(ClassA.class::cast)
                .collect(Collectors.toList());*/
        List<ClassA> classA=(List<ClassA>)(Object)objects;
        addDataToExcel(classA);

    }
    else if(objects instanceof ClassB){
        ClassB classb=(ClassB) objects;
    }
    else if(objects instanceof ClassC){
        ClassC classc=(ClassC) objects;
    }

    return response;

}
Selaron
  • 6,105
  • 4
  • 31
  • 39
Sagar Chidre
  • 5
  • 1
  • 7
  • Possible duplicate of [How to cast List to List](https://stackoverflow.com/questions/1917844/how-to-cast-listobject-to-listmyclass) – Mebin Joe Apr 08 '19 at 11:27
  • I want do it without casting – Sagar Chidre Apr 08 '19 at 11:49
  • This might help. https://stackoverflow.com/questions/8933434/how-to-cast-listobject-to-listsomethingelse/8933474 – Mebin Joe Apr 08 '19 at 12:04
  • i tried it but not working – Sagar Chidre Apr 08 '19 at 12:15
  • When you want to write “a generic method which accepts any type to List of Objects”, a parameter type of `List` is wrong, as that will only accept lists of precisely `Object` and nothing else. `List>` would accept any element type. However, a method that can handle only three types should not pretend to be able to handle any type… – Holger Apr 08 '19 at 13:20
  • Is there any other way without downcasting – Sagar Chidre Apr 09 '19 at 03:22
  • What is the issue exactly .... the ```if ... instanceof``` statement won't compile in the first place... can you please clean the code to something that work with the downcast and then perhaps a separated snippet with you would like to have but does not work, is it simply ```(List)(Object)objects``` vs ```(List)objects```? – Valentin Ruano Apr 09 '19 at 17:36

0 Answers0