简体   繁体   中英

How can I call an instance method from a generic object?

Say I have an arrayList containing items of different classes, all of them having the same method: draw(); I have a third class with a method drawItems() that takes in the arrayList as a parameter. Now, how can I call the draw() method on those objects if they are passed as generic objects?

This below doesn't work. I can see why. Java doesn't know the item has such a function. How can I get around this?

public void drawItems(ArrayList<T> data) 
{
    data.forEach((T item) -> {
        item.draw();
   }); 
}

UPDATE

Thank you everyone. I did it as follows:

1) Create interface named Drawable:

public interface Drawable {
    public void draw();
}

2) Implement interface into Item class:

public class Item implements Drawable { 

    @Override
    public void draw(GraphicsContext gc) {
        //...
    }
}

3) Adjust drawItems:

public void drawItems(ArrayList<Drawable> data) {

    data.forEach((Drawable item) -> {
        item.draw();
    });
}

Your T type parameter is unbounded, so the compiler makes no assumptions about the methods guaranteed to be available (except for Object methods). That's why it can't find the draw method.

Do your classes that have the draw method inherit from some superclass or interface that declares the draw method? If not, create that interface, eg Drawable .

Then change the parameter data to be of type List<? extends Drawable> List<? extends Drawable> , so you can pass in a List<Drawable> or eg a List<DrawableSubclass> .

If instead you must use the type parameter T , declare T (I'm assuming it's on the class) to be T extends Drawable .

Either way, with the upper bound, everything in the List will be Drawable , so the compiler knows that any objects in that list will have a draw method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM