Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting - foreach - java

I have a one method like this:

private void myMethod(List<?> myLists) {

   for (Object val : myLists) {
       val.getMyOtherMethod(); // for example
   }

}

How can I casting val to one of my objects?

All my objects (list objects) contain same methods, like as getMyOtherMethod()

BR

edit: ---------------------------------------------------------------------

I called myMethod few times, like as:

List<MyClas.MySubclass1> var1;
List<MyClas.MySubclass2> var1;
List<MyClas.MySubclass3> var1;
...
...

myMethod(var1);
myMethod(var2);
myMethod(var3);

In this case, I do not know, witch subclass I send MySubclass1, MySubclass2 or MySubclass3. That is important for foreach loop.

like image 987
Kolesar Avatar asked Jul 18 '26 09:07

Kolesar


1 Answers

You need a List of elements which implement getMyOtherMethod()

interface ImplementsGetMyOtherMethod {
   void getMyOtherMethod();
}

private void myMethod(List<? extends ImplementsGetMyOtherMethod> myLists) {
like image 134
Peter Lawrey Avatar answered Jul 20 '26 22:07

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!