![](/img/trans.png)
[英]Is there a way to pass different (but specific) types of objects in same method and have different ways to handle based on the type of object
[英]Is there a way to create different type objects with same method?
我有3个存储库和3个类。
有没有一种方法可以创建“帮助程序”方法来创建每种类型的对象并将其添加到这些存储库中? 每个存储库都有其各自对象的ArrayList。
例如:
public static void createAnObject(int numberOfObjects, Object type){
// Create number of objects based on the number and type of object
}
是的,您可以执行以下操作:
A)向您的方法中添加一个通用类型参数,指定要返回的对象类型,如上面的注释中所述。
B)让该方法返回“ java.lang.Object”的实例,这使它能够返回任何类型的对象。 如果您知道何时创建的对象,则只需将返回的对象转换为要选择对其进行操作的对象,其功能将与将对象类型设置为对象的返回类型时完全相同。您的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.