简体   繁体   中英

Is there a way to create different type objects with same method?

I have 3 repositories and 3 classes.

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.

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.

B) Have the method return an instance of "java.lang.Object", this gives it the ability to return any type of 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.

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