[英]Is there a way to create different type objects with same method?
I have 3 repositories and 3 classes. 我有3个存储库和3个类。
Is there a way to create a "helper" method to create object of each type and add to those repositories? 有没有一种方法可以创建“帮助程序”方法来创建每种类型的对象并将其添加到这些存储库中? Each repository has an ArrayList of their respective objects.
每个存储库都有其各自对象的ArrayList。
For example: 例如:
public static void createAnObject(int numberOfObjects, Object type){
// Create number of objects based on the number and type of object
}
Yes, you can do things like: 是的,您可以执行以下操作:
A) Add a generic type parameter to your method, specifying which object type you wish to return, as someone stated in the comments above. A)向您的方法中添加一个通用类型参数,指定要返回的对象类型,如上面的注释中所述。
B) Have the method return an instance of "java.lang.Object", this gives it the ability to return any type of object. B)让该方法返回“ java.lang.Object”的实例,这使它能够返回任何类型的对象。 If you know what object is being created when, you can simply cast the returned object to the one you are choosing to operate on and, it will function exactly the same as it would if you were to set that objects type as the return type for your method.
如果您知道何时创建的对象,则只需将返回的对象转换为要选择对其进行操作的对象,其功能将与将对象类型设置为对象的返回类型时完全相同。您的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.