elCapitano
elCapitano

Reputation: 1841

Create list of subclass elements in java generics

i saw that those reflection problems are discussed a lot here. Unfotunately i couldnt find any solution for my problem:

I have one abstract class which handles a lot of stuff for the sublcasses

public abstract class A{
    public static <T extends A> create(){
        // some factory stuff here
    }
    public static List<....> createMore(){ /// some stuff here}
}

The class A is located in a included library of the main project. Now i want to use the methods of A for the sub classes of A:

 public class A1 extends A {...}

and use it:

   A1 mySubclass = A1.create();
   ArrayList<A1> listOfSubclass= A1.createMore();

Is this possible in any way?

Upvotes: 0

Views: 353

Answers (1)

newacct
newacct

Reputation: 122538

createMore is possible:

public static <T extends A> List<T> createMore(){
    return new ArrayList<T>();
}

create is only (correctly) possible if you return null:

public static <T extends A> T create(){
    return null;
}

Without any input, there is no way that that function can decide what to return. And it must match whatever type the caller scope wants at compile time, without knowing what that is.

Upvotes: 1

Related Questions