将子类传递给方法但是以超类作为参数? [英] Passing in a sub-class to a method but having the super class as the parameter?

查看:108
本文介绍了将子类传递给方法但是以超类作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类 Vehicle ,其中包含2个已实现的子类 RedVehicle YellowVehicle

I have an abstract class Vehicle with 2 implemented subclasses RedVehicle and YellowVehicle.

在另一个类中,我有一个 List< Vehicle> ,其中包含两个子类的实例。
我希望能够传递一个类类型的方法然后使用该类型来决定我想在列表中执行某些操作的对象

In another class I have a List<Vehicle> containing instances of both subclasses. I want to be able to pass into a method a class type and then use that type to decide which set of objects I want to do something to in the List.

由于 Class 是通用的,我应该用它来参数化,但是把参数作为父类 Vehicle 停止调用代码工作,因为 exampleMethod 现在需要一种Vehicle类型,而不是的子类RedVehicle YellowVehicle

Since Class is generic I should parameterise it with something, however putting the parameter as the parent class Vehicle stops the calling code working since exampleMethod is now expecting a type of Vehicle, not a subclass of RedVehicle or YellowVehicle.

我觉得应该有一个干净的方法来做到这一点那么实现该功能的正确方法是什么?

I feel there should be a clean way to do this so what would be the correct way to implement the functionality?

n.b。我不一定要传递 Class 类型,如果有更好的建议,我会很乐意尝试这些。

n.b. I don't necessarily have to pass in the Class type, if there are better suggestions I'd be happy to try those.

调用代码:

service.exampleMethod(RedVehicle.class);
service.exampleMethod(YellowVehicle.class);

字段/方法:

//List of vehicles
//Vehicle has 2 subclasses, RedVehicle and YellowVehicle
private List<Vehicle> vehicles;

//Having <Vehicle> as the Class parameter stops the calling code working
public void exampleMethod(Class<Vehicle> type) 
{
    for(Vehicle v : vehicles)
    {
        if(v.getClass().equals(type))
        {
            //do something
        }
    }
}


推荐答案

请改为:

public <T extends Vehicle> void exampleMethod(Class<T> type) 

这篇关于将子类传递给方法但是以超类作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆