简体   繁体   English

具有接口和抽象类的Java通用设置器

[英]Java Generic Setter with Interface and Abstract Class

i have a problem with an Interface and generic setters that i tried to solve for some hours now. 我现在尝试解决几个小时的接口和通用设置器有问题。

i have an interface where i want to define some getter and setter functions. 我有一个接口,我想定义一些getter和setter函数。 the getter functions should be implemented by some abstract class since they usually shouldn't change. getter函数应该由某些抽象类实现,因为它们通常不应更改。 the setter functions on the other hand should be overrideable multiple times by a defined class. 另一方面,setter函数应被定义的类多次重写。 In the case i try to describe it would be that the childClass should be able to implement 2 setFunctions with the same name and different input values 在我尝试描述的情况下,childClass应该能够实现两个具有相同名称和不同输入值的setFunctions

 Interface TestClass {     
      public abstract void setSomething(List<?> value);
      public abstract List<String> getSomething();
 }

 abstract class AbstractTestClass  implements TestClass {

      List<String> someData;

      public List<String> getSomething() {
          return someData;
      }
 }

 class TestClassImplementation extends AbstractTestClass() {

      @Override
      public void setSomething(List<String> data) {
         someData = data;
      }

      @Override
      public void setSomething(List<SomeOtherType> data) {
         someData = convertToStringList(data);
      }

      private List<String> convertToStringList(List<SomeOtherType> data) {
         ... do some conversion ...
         return returnList;
      }
 }

hope this gives the idea of what i want to do. 希望这能给出我想要做什么的想法。 I would even prefer to implement the setSomething with the stringlist in the abstract class. 我什至更喜欢用抽象类中的字符串列表实现setSomething。 But both setters must be reachable. 但是两个设置者必须是可及的。 Thanks 谢谢

You simply can't do that. 你根本做不到。 Generics are not retained at runtime (google type erasure for more infos on this or just read the wikipedia page). 泛型不会在运行时保留(有关此内容的更多信息,请谷歌类型擦除或仅阅读Wikipedia页面)。

This means that your setSomething-methods all have the same signature, as their only parameter is of type List . 这意味着您的setSomething方法都具有相同的签名,因为它们的唯一参数是List类型。

Well, you should try with generic solution: 好吧,您应该尝试使用通用解决方案:

Interface TestClass<T> { //Generic type T that you will provide when extending with actual class

    public abstract void setSomething(List<T> value);
    public abstract List<T> getSomething();
}

class TestClassImplementation extends AbstractTestClass<RealType> {

    @Override
    public void setSomething(List<RealType> data) {
       someData = data;
    }
}

The thing that confuses you is that the wildcard sign ? 令您感到困惑的是通配符 ? does not mean it changes any type, it just denotes an unknown type. 这并不意味着它会更改任何类型,而只是表示未知类型。

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

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