Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 842
tbeernot Avatar asked Oct 28 '25 07:10

tbeernot


1 Answers

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());
    }
}
like image 148
samabcde Avatar answered Oct 31 '25 12:10

samabcde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!