Rylander
Rylander

Reputation: 20119

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
        }
    }
}

Upvotes: 3

Views: 78

Answers (2)

Tunaki
Tunaki

Reputation: 137064

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
    }
}

Upvotes: 7

Makoto
Makoto

Reputation: 106400

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) { }

Upvotes: 6

Related Questions