简体   繁体   English

从接口返回类型的通用方法

[英]Generic method with return type from interface

I have an interface and a value class that look like this: 我有一个接口和一个看起来像这样的值类:

public interface ITest<T1> {
  <T2> T1 test(OtherClass<T2> client);
}

Basically, it says that subtypes have to implement the method test that returns a T1, whatever that is in the implementing subtype. 基本上,它表示子类型必须实现返回T1的方法test ,无论实现子类型中是什么。

OtherClass: OtherClass:

public class OtherClass<T> {
  public T contents;  
}

However, when I want to write a subtype that implements test and just returns the client instance it gets, I get compile errors. 但是,当我想编写一个实现test的子类型并且只返回它获得的客户端实例时,我会遇到编译错误。 What I want is unify T1 and T2 : 我想要的是统一T1T2

public class Test<T1> implements ITest<T1> {
  @Override
  public <T1> T1 test(OtherClass<T1> client) { // compile error
    return client.contents;
  }
}

Is there any way to get this class to work? 有没有办法让这个班上班?

I don't think think this is allowed since you are now restricting the T2 to be a T1 in the class Test<T1> . 我不认为认为这是允许的,因为你现在限制T2是一个T1类中的Test<T1>

You can solve this problem as follows: 您可以按如下方式解决此问题:

public interface ITest<T1, T2> {
    T1 test(OtherClass<T2> client);
}

public class OtherClass<T> {
  public T contents;  
}

public class Test<T1> implements ITest<T1, T1> {
    @Override
    public T1 test(OtherClass<T1> client) {
        return client.contents;
    }
}

<T1> basically tells any class "you pick what type T1 is going to be!". <T1>基本上告诉任何一个班级“你选择T1将是什么类型!”。 This means that in this case <T1> and OtherClass<T1> refer to the same type, while the return type T1 refers to the class's T1 . 这意味着在这种情况下, <T1>OtherClass<T1>指的是相同的类型,而返回类型T1指的是类的T1 If you rename one you will see the error: 如果重命名,您将看到错误:

@Override
public <OtherClassType> T1 test(OtherClass<OtherClassType> client) {
    return client.contents; //you can't do that without casting OtherClassType to T1
}

If you cannot edit the ITest interface, the only way for this to compile would be by casting, but you need to make sure that you can actually cast before doing so (because OtherClass can return any type, not necessarily a subclass of T1. 如果你不能编辑ITest接口,那么编译它的唯一方法就是通过强制转换,但你需要确保在执行之前可以实际执行(因为OtherClass可以返回任何类型,不一定是T1的子类)。

EDIT: The exact reason the compiler does not allow this is because you are effectively restricting the test method to only take in certain types, while the method it is overriding allows for any type. 编辑:编译器不允许这样做的确切原因是因为您实际上限制了test方法只接受某些类型,而它重写的方法允许任何类型。

In your interface declaration, you say that you want you test function to accept any type (you did not specify any bounds for T2 ). 在您的接口声明中,您说您希望test函数接受任何类型(您没有为T2指定任何边界)。

In your implementation you only accept T1 , which is not any type. 在您的实现中,您只接受T1 ,这不是任何类型。

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

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