使用标记接口来限制通用参数

Won*_*ano 5 java generics interface

我有一个 Foo 类,它可以处理某种类型的变量。我想将这种类型限制在我拥有的几个课程中。这些类已经实现但没有任何继承关系。编写一个空接口 Type,然后将“实现类型”添加到作为泛型参数 T 的可接受类型的所有类是否有意义。

这意味着你会得到这样的东西:

public class SuperFoo() {
    //Some code
}

public class Foo<T extends Fooable> extends SuperFoo {
    private T acceptedObject;
    private String name;

    public Foo(String name, T acceptedObject) {
        this.name = name;
        this.acceptedObject = acceptedObject;
        //Some code
    }
}

public interface Fooable {}

public class FooableClass1 implements Fooable {  //Objects of this class will be accepted as T
    public FooableClass1() {}
    //Some code
}

public class FooableClass2 implements Fooable { //Object of this class will also be accepted as T
    public FooableClass1() {}
    //Some code
}

public class AnotherClass { //Objects of this class will not be accepted as T
    //Some code
}
Run Code Online (Sandbox Code Playgroud)

编辑:感谢您的回答,我更改了上面的代码。我对这部分代码还有一个问题。如果我想在另一个类中实现一个方法来创建 SuperFoo 类(Foo 的超类)的新实例,我该怎么做?

这个方法类似于:

public SuperFoo createNewFoo(String name, Type type) {
    //Calls the constructor of Foo and returns the object but how?
    //The type parameter decides whether the constructor of FooableClass1 
    //or the constructor of FooableClass2 is called.
}
Run Code Online (Sandbox Code Playgroud)

我将如何实现类 Type?此类的对象仅包含有关对象应属于哪种 Fooable 类型的信息。

Cap*_*Man 0

我建议打个interface电话FooableSerializablejava api 中就是一个很好的例子,这是一个强有力的论据,证明这是正确的。