接受两种不同类型作为参数的方法 [英] Method accepting two different types as parameter
问题描述
我正在编写一个方法,该方法应该接受两个类型之一的对象,它们不共享除Object以外的父类型。例如,类型是梦和大蒜。您可以同时执行 dreams.crush()
和 garlic.crush()
。我想要一个方法 utterlyDestroy(参数)
,它可以接受Dreams和Garlic作为它的参数。
utterlyDestroy(parameter){
parameter.crush()
}
大蒜和梦都是某个库的一部分,所以让它们实现一个接口ICrushable(这样我就可以编写 utterlyDestroy(ICrushable参数)
)不是一个选项。
我的方法体很长,所以重载它意味着重复代码。丑陋。
我确定我可以使用反射并进行一些课堂黑客。丑陋。
我尝试使用泛型,但显然我不能写类似于
utterlyDestroy(< T instanceof Dreams || T instanceof Garlic>参数)
typecast Garlic to Dreams?
utterlyDestroy(Object parameter){
((Dreams)parameter).crush()
}
尽管如此,这仍然很难看。什么是我的其他选择,以及处理这种情况的首选方法是什么?
接口ICrushable {
void crush();
}
utterlyDestroy(ICrushable参数){
//非常长的粉碎过程在这里
parameter.crush()
}
utterlyDestroy(Dreams parameter){
utterlyDestroy(new ICrushable(){crush(){parameter.crush();});
utterlyDestroy(Garlic parameter){
utterlyDestroy(new ICrushable(){crush(){parameter.crush();});
$ b新的开发应该实现ICrushable接口,但是对于现有的类,参数被包装在一个ICrushable中,并传递给完成所有工作的utterlyDestroy(ICrushable)。
I am writing a method that should accept as its parameter an object of one of two types which do not share a parent type other than Object. For example, the types are Dreams and Garlic. You can do both dreams.crush()
and garlic.crush()
. I want to have a method utterlyDestroy(parameter)
, that would accept as its parameter both Dreams and Garlic.
utterlyDestroy(parameter) {
parameter.crush()
}
Both Garlic and dreams are a part of some library, so having them implement an interface ICrushable (so that I could write utterlyDestroy(ICrushable parameter)
) is not an option.
My method body is quite long so overloading it would mean duplicating code. Ugly.
I am sure I could use reflection and do some class hacking. Ugly.
I tried using generics but apparently I cannot write something like
utterlyDestroy(<T instanceof Dreams || T instanceof Garlic> parameter)
Is it possible to typecast Garlic to Dreams?
utterlyDestroy(Object parameter) {
((Dreams)parameter).crush()
}
This would still be ugly though. What are my other options and what is the preferred method of dealing with the situation?
解决方案 How about this:
interface ICrushable {
void crush();
}
utterlyDestroy(ICrushable parameter) {
// Very long crushing process goes here
parameter.crush()
}
utterlyDestroy(Dreams parameter) {
utterlyDestroy(new ICrushable() { crush() {parameter.crush();});
}
utterlyDestroy(Garlic parameter) {
utterlyDestroy(new ICrushable() { crush() {parameter.crush();});
}
New development should implement the ICrushable interface, but for the existing Classes, the parameter is wrapped in an ICrushable and passed to the utterlyDestroy(ICrushable) that does all the work.
这篇关于接受两种不同类型作为参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!