简体   繁体   English

具有不同具体类型的接口实现作为方法参数

[英]interface implementations with different concrete types as method parameters

I would like to have a method in an interface that accepts any Type of a generic object, like 我想在接口中有一个接受任何类型的通用对象的方法,比如

public void myMethod(List<?>);

Now the implementations should only accept a certain type, eg. 现在实现应该只接受某种类型,例如。 implementations 1: 实现1:

public void myMethod(List<Integer>);

Implementation 2: 实施2:

public void myMethod(List<String>);

However this does not work as public void myMethod(List<Integer>); 但是这不起作用public void myMethod(List<Integer>); is not a valid implementaion of public void myMethod(List<?>); 不是public void myMethod(List<?>);的有效实现public void myMethod(List<?>);

How could I achieve this? 我怎么能实现这个目标? (Besides using an Object Parameter and hence rely on casting and do type checking manually) (除了使用对象参数,因此依赖于转换并手动进行类型检查)

Unless I'm missing something obvious (which happens too much for my liking), why not make the interface itself generic? 除非我遗漏了一些明显的东西(这对我的喜好太多了),为什么不让界面本身通用呢?

public interface MyInterface<T> {
   public void myMethod(List<T> list);
}

Which can be implemented like so: 哪个可以像这样实现:

public class MyClass<T> implements MyInterface<T> {

   @Override
   public void myMethod(List<T> list) {
      // TODO complete this!      
   }

}

and used like so: 并使用如下:

public class Foo {
   public static void main(String[] args) {
      MyClass<String> myString = new MyClass<String>();
      MyClass<Integer> myInt = new MyClass<Integer>();
   }
}

You may want to you types: http://docs.oracle.com/javase/tutorial/java/generics/gentypes.html 你可能想要你的类型: http//docs.oracle.com/javase/tutorial/java/generics/gentypes.html

for example, use public void myMethod(List<T>); 例如,使用public void myMethod(List<T>);

for your interface, and then your concrete classes are instatiated with the type you want. 对于您的界面,然后您的具体类使用您想要的类型进行实例化。 ` `

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

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