简体   繁体   English

如何确定Java泛型是否实现特定接口?

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

How can I determine if a Java generic implements a particular interface? 如何确定Java泛型是否实现特定接口?

I have tried a few different approaches, but they all results in a "cannot find symbol ... variable T" error. 我尝试了几种不同的方法,但它们都导致了“无法找到符号......变量T”的错误。

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 解决方法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 解决方法2

Add a constraint to the type T with T extends SomeInterface , thereby restricting the type T to be a subtype of SomeInterface . T类型添加约束,使用T extends SomeInterface ,从而将类型T限制为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. 然后,当你作为方法的参数传递时,你保证它至少是 SomeInterface

From your approach, there's no way to do it, since you don't reference an instance of T anywhere in your code. 从您的方法来看,没有办法,因为您没有在代码中的任何位置引用T的实例。 If you added an argument to it, you'd be able to at least get further. 如果你为它添加了一个参数,你至少可以得到更多。

public void doFoo(T obj) { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM