Java casting Arrays
I wrote a simple library in which the user extends one of my abstract classes and then passes t开发者_如何学Gohat class to one of my functions.
//user class
class My_robot extends Robot{
}
//My library function
function Robot_maker("path.to.My_robot")
The robot maker function then creates an array of the type Robot[]
. The user then can have the array returned to them by calling another one of my functions Robot[]
get_robot_army()
I know that I can cast the Robot[]
array element by element but is there a way to cast the entire array at once? (I want to abstract this away from the end user)
Is there a way to use Reflection to change the return type of a function?
///////////////////////////// There is some need for clarity ///////////////////////////
The code in question is the function batch_result() on line 124 I want to be able to return the class that the user supplied using the function batch_set_relationship() on line 139 As an example if some one ran here on line 88 how can I pass the user an array of the supplied custom supplied class.Also can some one clarify why the cast to an array of a different type fails.
Responding to the comments above:
I would just return the Robot[] array and cast each element of that array.
As I said before, cast to what? And why? The return type of the user's function should be Robot[]. The user sublasses Robot to do what they need to do, and returns Robot[] containing instances of their subclass. Your code doesn't need to know what the subclass is; that's the whole point of polymorphism.
One way you can think, add the complete array into an list or any collection and send that as a return type
In that way you can achieve the casting of return type.
With the reflection class you cant change the class type but you can defnitely get the class type dynamically, then later you need to modofy the class type to meet your requirements
精彩评论