Reputation: 1289
If I am writing a wrapper for a generic class, which I have tried to embed the type into at construction (as in this SO question):
class Foo<T> {
private T value;
private Class<T> type;
public Foo(Class<T> type, T value) {
this.value = value;
this.type = type;
}
public T getValue() {
return value;
}
public Class<T> getType() {
return type;
}
}
I have a list of instances of Foo
, which I want to transform into a list of FooWrapper
s, along these lines:
List<Foo<?>> someListOfFoos = ...
List<FooWrapper<?>> fooWrappers = someListOfFoos
.stream()
.map(foo -> FooWrapper.from(foo))
.collect(Collectors.toList());
Is there any way to recover the type of each element in someListOfFoos
when building each FooWrapper
? Something along these lines:
class FooWrapper<T> {
private Foo<T> foo;
public static FooWrapper<?> from(Foo<?> toWrap) {
Class<E> type = toWrap.getType(); // i know this is wrong
return new FooWrapper<type>(toWrap); // this is very wrong
}
private FooWrapper(Foo<T> foo) {
this.foo = foo;
}
}
Upvotes: 1
Views: 252
Reputation: 4841
You just have to modify your FooWrapper#from
slightly, by introducing a generic:
public static <E> FooWrapper<E> from(Foo<E> toWrap) {
return new FooWrapper<E>(toWrap);
}
Upvotes: 4