我希望能够检查对象是否是扩展特定父类的类的实例。下面是我编写的代码的相关部分。我希望根据特定子类型的aggType设置aggDef变量。我知道我不能像下面代码中所示的那样做下面的事情,但是有什么技术我可以遵循来完成这种功能吗?,不幸的是,正确的面向对象设计不是一个选项,我可以在父程序中定义一个抽象方法,并且让孩子知道他们是哪种类型,因为这些都是专有的、不可访问的内部库。
String aggType=null;
AggDef aggDef = queryAggs.get(aggsKey);
if(aggDef != null){
if(aggDef instanceof TermAggDef){
aggType = "terms";
}
else if (aggDef instanceof ? extends StatAggDef){
aggType = "terms_stats";
}
else if (aggDef instanceof RangeAggDef){
aggType = "range";
} else{
aggType= "statistical";
}
}
}另一种选择是我在下面的方法,它确实编译和工作。但这既乏味又丑陋。这又如何改善呢?
String aggType;
AggDef aggDef = queryAggs.get(aggsKey);
if(aggDef != null){
if(aggDef instanceof TermAggDef){
aggType = "terms";
}
else if (aggDef instanceof StatAggDef){
if(aggDef instanceof AvgAggDef){
aggType= "statistical";
}else if(aggDef instanceof MaxAggDef){
aggType= "statistical";
}else if(aggDef instanceof MinAggDef){
aggType= "statistical";
}else if(aggDef instanceof SumAggDef){
aggType= "statistical";
} else{
aggType = "terms_stats";
}
}
else if (aggDef instanceof RangeAggDef){
aggType = "range";
}
}发布于 2015-08-18 23:29:06
让自己成为一个Map<Class<? extends AggDef>, String>;填充它;并通过aggDef.getClass()来查找它,而不是if- the /instanceof链。
发布于 2015-08-18 23:09:26
为什么不直接写一些面向对象的代码,比如:
public abstract class AggDef { // horribly named class
public abstract Type getType();
...
}并在每个子类上重写该方法。
public class StatAggDef extends AggDef {
@Override
public Type getType() {
//something concrete, ideally not a String....
}
}当您添加新类型时,这是更可扩展的。使用instanceof是一个很好的指示,表明您没有真正正确地建模您的应用程序。
https://stackoverflow.com/questions/32084003
复制相似问题