简体   繁体   中英

Bound mismatch in Java for generic method

I can't understand why I'm getting this compilation error

Bound mismatch: The generic method element(T) of type Resource is not applicable for the arguments ( Class<Chassis> ). The inferred type Class<Chassis> is not a valid substitute for the bounded parameter <T extends Resource> .

with the following code:

public class Resource {
    protected abstract class has<T extends Resource> {
        public has(T v) {}
    }

    protected <T extends Resource> has element(T v) {
        return new has<T>(v) {};
    }
}

class Car extends Resource {
    has chassis = element(Chassis.class);
}

class Chassis extends Resource {
}

Why is this invalid? Chassis extends Resource , so why doesn't match to <T extends Resource> ?

And how could I constraint element() method to accept as an argument a Resource class object or any Resource subclass object?

Chassis.class is an instance of java.lang.Class , which only extends java.lang.Object .

The <T extends Resource> expects an actual instance of Resource (or one of its subclasses).

To solve this, you can change your method declaration to the following:

protected <T extends Resource> has element(Class<T> v) {
    return new has<T>(v) {};
}

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