Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Java generics, how to work around type erasure?
Post
Java generics, how to work around type erasure?
+4
−0
This code doesn't compile:
package tryNcry;
public class ExampleClass<S extends SomeClass> {
S[] createArray(int n) {
return new S[n]; // obvious compile time ERROR here:
// Cannot create a generic array of S
}
}
The reason for this is obvious: due to type erasure, at runtime there is no way for the JRE to know what S would have been, and so no way to create an array for type S.
Everything would be fine (if tedious) if there was any instance of S, using reflection.
How can I solve this?

1 comment thread