mikeg9
mikeg9

Reputation: 21

How to Instantiate a generic class with the given type when given type is an Array

say i have these classes:

class B<T> {}

class A<T> {

}

Instantiating A:

A<Float[]> a = new A<>();

In A's constructor I want to initialize B class with the type of T but not as an Array

B<Float> b = new B<>();

Upvotes: 1

Views: 51

Answers (1)

JakeRobb
JakeRobb

Reputation: 1960

Without knowing more details, I'm not 100% sure this can work, but:

Change the generic type argument of A to be just Float, not Float[]. Then, on A's methods that take/return T, change them to specify T[].

If that doesn't work for you, your alternatives are: * use reflection (somewhat pointless, as generic type enforcement is compile-time only in Java) * use compatible superclasses and casting (syntax fairly obnoxious, and you'll get little to no help from the compiler) * use plain, unparameterized types (syntax is fine, still no help from the compiler)

If you edit your question to include more details, I'm happy to edit this to provide more specific guidance.

Upvotes: 1

Related Questions