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.
Post History
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: ...
#2: Post edited
Java generics, how to work around type erasure?
Look at my code:```- 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: *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 instant of "S", using reflection.What is the intended way to solve this?
- This code doesn't compile:
- ```java
- 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: Initial revision
Java generics, how to work around type erasure?
Look at my code:
```
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: *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 instant of "S", using reflection.
What is the intended way to solve this?
