简体   繁体   English

接口中的通用类型和实现中的非通用类型

[英]Generic Types in Interface and Non Generic in Implementation

I wasn't sure how to properly name this question, so if its better suited to be edited, please do so. 我不确定如何正确地命名这个问题,所以如果它更适合编辑,请这样做。 My question has to do with using generic types in an interface and then forcing the implementation into a specific type. 我的问题与在接口中使用泛型类型然后强制实现到特定类型有关。 Something like this: 像这样的东西:

public interface Test<T> {
    void testMethod(Object<T> obj);
}

And then instead of allowing a generic object in an implementation of this interface, set the type somehow. 然后,不是在此接口的实现中允许通用对象,而是以某种方式设置类型。

public class TestImpl implements Test<TestObject1> {
    @Override
    public void testMethod(TestObject1 obj) {
        //Do something
    }
}

public class Test2Impl implements Test<TestObject2> {
    @Override
    public void testMethod(TestObject2 obj) {
        //Do something
    }
}

Except you cannot paramaterize Object and i'm not sure how to set this sort of thing up. 除非你不能使用对象,我不知道如何设置这类东西。 Is it even possible? 它甚至可能吗? Right now I just use generic Object, but that leaves me being forced to check the type of class being passed in for every single method and/or casting etc etc. It would be so much cleaner if I could just use generics on the interface and then specific classes on the implementation. 现在我只使用通用对象,但这让我不得不检查每个方法和/或转换等传入的类的类型。如果我可以在接口上使用泛型,那将会更加清晰。然后是关于实现的特定类。

public interface Test<T> {
    void testMethod(T obj);
}

You were close. 你很亲密

Then you can either write your classes the way you have them if testMethod is specific to the Class being passed in, or ... 然后,如果testMethod特定于传入的类,您可以按照它们的方式编写类,或者......

public class TestImpl<T> implements Test<T> {
    @Override
    public void testMethod(T obj) {
        //Do something
    }
}

Now you can instantiate your class via new TestImpl<TestObject>() or new TestImpl<TestObject2>() 现在,您可以通过new TestImpl<TestObject>()new TestImpl<TestObject2>()来实例化您的类

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

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