简体   繁体   English

有没有办法用相同的方法创建不同类型的对象?

[英]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.

相关问题 有没有办法在同一方法中传递不同(但特定)类型的对象,并根据 object 的类型有不同的处理方式 - 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 在同一方法上动态传递不同类型的对象 - passing different type of objects dynamically on same method 创建具有相同基本类型的不同对象。工厂模式? - Create different Objects with same base type. Factory pattern? 我如何在具有不同构造函数的方法中创建给定对象类型的对象 - how I create objects of the given object type in a method with different constructors 为不同的参数和类型编写具有相同业务逻辑的方法的最佳方法? - Best way to write method with same business logic for different parameters and type? 根据类型创建不同的对象 - Create different objects depending on type 如何对方法名称不同但返回类型相同的不同对象应用相同的过程 - How to apply same process for differents objects with different method name but same returned type 相同方法的不同返回类型 - Different return type for the same method 在同一TCP套接字上接收不同类型的对象 - Recive different type of objects on the same TCP socket Java不同类型的对象作为相同的参数 - Java different type objects as same parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM