简体   繁体   中英

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.

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM