简体   繁体   English

对自定义类型使用泛型

[英]Using generic for custom type

I am working with some methods that write every type in a custom way. 我正在使用一些以自定义方式编写每种类型的方法。 These are the signatures: 这些是签名:

public void write(Boolean value);
public void write(Byte value);
...
public void write(Integer value);
public void write(Long value);

As the signatures are the same but changing the type, I have been thinking on using generics and a method that receives an unknown type and uses the correct method. 由于签名是相同的,但是更改了类型,所以我一直在考虑使用泛型和一种接收未知类型并使用正确方法的方法。 Something similar to this: 类似于以下内容:

public <T> void doWrite(T data) {
    write(data);
}

In this case the compiler gives me this error: 在这种情况下,编译器给我这个错误:

The method write(Boolean) in the type Writer is not applicable for the arguments (T).

Any hint on how could I do it ? 关于我该怎么做的任何提示?

As a rule of thumb, you should consider using generics when your code gets a lot of type querying (casts, instanceof). 根据经验,当代码中进行大量类型查询(casts,instanceof)时,应考虑使用泛型。 The purpose is to eliminate this casting. 目的是消除这种铸造。 Your case seems not to be of this kind. 您的案件似乎不是这种情况。 On the contrary you will introduce this type querying by refactoring your code the way you ask, so I don't think it is apropriate 相反,您将通过按要求的方式重构代码来引入这种类型的查询,所以我认为这不合适

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

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