使用标记接口来限制泛型参数

时间:2015-05-22 14:32:10

标签: java generics interface

我有一个类Foo,它可以处理某种类型的变量。我想将这种类型限制为我拥有的几个类。这些类已经实现但没有任何继承关系。编写一个空接口Type然后将'implements 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
}
编辑:谢谢你的答案,我改变了上面的代码。我对这部分代码还有一个问题。如果我想在另一个类中实现一个方法来创建类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.
}

我如何实现类Type?这个类的一个对象只包含一个对象应该是哪种类型的Fooable的信息。

1 个答案:

答案 0 :(得分:0)

我建议制作名为interface的{​​{1}}。 Serializable是java api中的一个很好的例子,这是一个强有力的论据,这是犹太人。