Fran Marzoa
Fran Marzoa

Reputation: 4544

Java generic method how to return a generic inner class

I know the title is quite messy, but I don't know how to explain this problem in just a few words.

Let:

public class A<T> {
    T foo;
    public A(T foo) {
        this.foo = foo;
    }

}

public class B {
    public A<T> getA() {
         ...
    }
}

Now, obviusly that B method won't even compile. The point is that I need a method in that B class that returns and A class, where the class T has to be passed to that method somehow so I can create an instance of T within such method in order to return an instance of A.

I tried something like:

public A getA(Class aClass) {
    return new A<aClass> ...
}

But that won't compile at all (aClass is unknown, it complains, and obviously it's right...)

So, how could I pass a class T to that method in order to create an instance of A inside it?

I hope you understand my question.

Thanks a lot in advance,

Upvotes: 1

Views: 268

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

Your non-generic implementation has the blueprint for the fix: change this

public A getA(Class aClass) {
    return new A<aClass> ...
}

to this:

public <T> A<T> getA(Class<T> tClass) {
//     ^^^  ^^^           ^^^
    return new A<T>(tClass.newInstance()); // Assumes T has a default constructor
}

Upvotes: 0

marstran
marstran

Reputation: 28036

You need a type-parameter for your function. Remember that you also need a parameter for A's constructor. This is the syntax:

public <T> A<T> getA(T t) {
    return new A<>(t);
}

Upvotes: 0

J Fabian Meier
J Fabian Meier

Reputation: 35825

You probably want to write a generic method:

https://docs.oracle.com/javase/tutorial/extra/generics/methods.html

public class B {
   public <T> A<T> getA() {
     ...
}

Upvotes: 1

Related Questions