Using Class<T> with immutables
I'm giving the immutables.org library a try. What I need is to be able to specify a class, so I've defined
@Value.Immutable
public interface Value<T> {
Class<T> getType();
}
The builder generated by immutables does not accept this
ImmutableValue.builder().type(String.class)...
Because it expects a Class<Object>. How do I get the builder to accept String.class?
Annotating the type with @Value.Parameter nicely creates a of method that works
ImmutableValue.of(String.class)...
But the result is an instance, not a builder, so follow up values can only be set using withers.
Solution 1:
You can infer the type using type witness.
public class ImmutableExample {
public static void main(String[] args) {
ImmutableValue immutableValue = ImmutableValue.<String>builder()
.type(String.class).build();
System.out.println(immutableValue.getType());
}
}