We have a C# code base that we have to deploy on Java.
We are creating a migration engine that reads C# and writes Java.
We have created stub class for the classes from system that are used in our code, and are implementing them.
When I came to do List<T>
in Java, I ran into problems while implementing ToArray
.
For what I understand, because of the major deference between Java and C# in terms of generics, there is no way of knowing the type of the generic class, and thus no way of creating a typed array.
Is this final, or any of you know of some clever way of doing ToArray
in a开发者_如何学C generic class without passing an array or a type as a parameter here or in the constructor.
We are creating a migration engine that reads c# and writes Java.
I hate to throw a monkey wrench into this plan, but this sounds like a truly wretched idea. You are going to wind up with an unidiomatic mess that will be difficult to maintain. It's the rough equivalent of running War and Peace through Google Translate and expecting to get a French version that means the exact same thing.
Lists in java have two toArray()
methods by contract.
- no-argument method, which returns
Object[]
- a method accepting an argument of type
T[]
.
The latter looks like this in its ArrayList
implementation (elementData
is the array backing the list):
public <T> T[] toArray(T[] a) {
if (a.length < size) {
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
}
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size) {
a[size] = null;
}
return a;
}
The parameter which is passed is described in the javadoc as follows:
the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
So in case you still want to implement a list yourself, follow this approach - i.e. create the array of the appropriate type beforehand and pass it to a generic method.
Probably you should have a look at Grasshopper and don't reinvent the wheel. It's a MSIL to Java bytecode compiler and it's a mature product.
You could look through the contents and find the most specific superclass of all elements. Of course, that could turn out to be more specific than the declared generic type, and what it should do with an empty list is an interesting question...
精彩评论