简体   繁体   中英

Java generic parameter as exact subclass?

Assuming we have a method like this:

public void foo(Class<? extends ClassBar> x) {
    ...
}

By modifying the generic expression;

< ? extends ClassBar >

Is it possible to ensure that ClassBar.class can't be passed in but anything extends ClassBar directly or indirectly be passed in throwing an exception on the runtime? 在运行时抛出异常?

If you have only a bunch of classes extending ClassBar you can follow these two approaches.


Solution 1:

have all subclasses of ClassBar extend a custom interface (except for ClassBar itself), and change the method signature to:

public <T extends ClassBar & MyInterface> void foo(Class<T> x) {
    ...
}

Solution 2:

use something similar to this @AndyTurner's trick and provide instances only for specific types.

Eg:

class ClassBar {}

class ClassBarA extends ClassBar{}
class ClassBarB extends ClassBar{}

Your class containing foo :

class Foo<T extends ClassBar> {
    private Foo() {} // private constructor

    public static <T extends ClassBarA> Foo<T> instance(T c) {
        return new Foo<T>();
    }

    public static <T extends ClassBarB> Foo<T> instance(T c) {
        return new Foo<T>();
    }

    public void foo(Class<T> c) {

    }

}

Only subclass of ClassBarA would be accepted in this case

Foo<ClassBarA> foo1 = Foo.instance(this.classBarA);
foo1.foo(ClassBarA.class); // pass
foo1.foo(ClassBar.class);  // fail

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