简体   繁体   中英

Generic object with builder pattern

I have a Producer<?, ?> producer field in my class, which implementation depends on a given state using a builder pattern, for example:

private void changeImplementation(int state) {
    switch (state) {
        case 0:
            producer = builder
                           .setKey(Long.class)
                           .setValue(String.class)
                           .setOtherStuff(...)
                           .build() // return the object with correct key and value
        break;
        case 1:
            ...
}

But whenever I call a method on producer (for example with types Producer<Long, String> ), this error is given (Eclipse EE):

The method method(Record<capture#9-of ?,capture#10-of ?>) in the type Producer<capture#9-of ?,capture#10-of ?> is not applicable for the arguments (Record<Long,String>)

Making a cast before build() or inside the method call didn't help. The build pattern works perfectly elsewhere in the project.

The problem is not related to the builder pattern, but rather that the type of your producer field is invoked with the unknown type ? . For this reason, you can only assign values to arguments of the generic types of Producer that are subtypes of the unknown type. However, the only value whose type is a subtype of ? is null , so it really limits what you can do with your Producer<?,?> .

To get around this you have to either bound your generic types of design things differently.

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