0

So basically I have List with some container, that contain generic object:

List<MyObj<?>> myObjList;

For example there can be MyObj<A> and MyObj<B>. And there some overloaded method todo(A a) and todo(B b). If i wanna call this method in cycle, I need hardcode casting to A or B:

for(MyObj<?> myObj: myObjList) {
    todo( (A) myObj.body() )
}

Is there a way to casting using class literal A.class?

I'm tried add class literal field to myObj:

class myObj<T> {
    Class<T> classLiteral;
    T body;
}

and use .cast() method:

for(MyObj<?> myObj: myObjList) {
    todo( 
         myObj.getClassLiteral().cast( myObj.body() )
    )
}

But it didn't work

BITniki
  • 3
  • 1
  • and how would it work if you would pass list of `C` with such autocast? – Antoniossss Jan 27 '23 at 10:55
  • 1
    "But it didn't work" - Compiler error, runtime exception? Please describe the output of your attempted approach. – Hulk Jan 27 '23 at 11:05
  • You can capture wildcards with helper functions (see e.g. [this related question](https://stackoverflow.com/questions/30763895/why-use-a-wild-card-capture-helper-method)). Also, within the methods of your `myObj`, you can use the type `T`. – Hulk Jan 27 '23 at 11:16
  • This question about [typesafe heterogeneous containers](https://stackoverflow.com/questions/58967845/typesafe-heterogeneous-containers-involving-generics) might also provide some inspiration. – Hulk Jan 27 '23 at 11:18
  • Sorry for missing. Compiler says: "no suitable method found for todo(capture#1 of ?)". I checked your links and learned a lot of new things. Thanks! I'm tried add some foohelper(), but got same error. `A` and `B` doesn't extends from each other and i can't change that since `A`, `B` and method `todo()` from external library. So seems like there no way for autocast. – BITniki Jan 28 '23 at 14:23

0 Answers0