Reputation: 4544
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
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
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
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