简体   繁体   中英

How can I determine if Java generic implements a particular interface?

How can I determine if a Java generic implements a particular interface?

I have tried a few different approaches, but they all results in a "cannot find symbol ... variable T" error.

First Attempt

public abstract class AbstractClass<T> {
    public void doFoo() {
        if (T instanceof SomeInterface){
            // do stuff
        }
    }
}

Second Attempt

public abstract class AbstractClass<T> {
    public void doFoo() {
        if (SomeInterface.class.isAssignableFrom(T)) {
            // do stuff
        }
    }
}

You can't.

Workaround 1

Add a constructor taking the class of the object.

public abstract class AbstractClass<T> {

    private Class<T> clazz;

    public AbstractClass(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void doFoo() {
        if (clazz instanceof SomeInterface){
            // do stuff
        }
    }
}

Workaround 2

Add a constraint to the type T with T extends SomeInterface , thereby restricting the type T to be a subtype of SomeInterface .

public abstract class AbstractClass<T extends SomeInterface> {
    public void doFoo() {
        // do stuff
    }
}

Put a bound on it.

public abstract class <T extends SomeInterface> { }

Then you're guaranteed that it will be at least SomeInterface when passed through as an argument to a method.

From your approach, there's no way to do it, since you don't reference an instance of T anywhere in your code. If you added an argument to it, you'd be able to at least get further.

public void doFoo(T obj) { }

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