Java条件运算符和不同类型 [英] java conditional operator and different types

查看:50
本文介绍了Java条件运算符和不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Item 类中有两个方法:

public void setValue(String v);
public void setValue(Double v);

,并且我想在其他类中使用 Conditional Operator setVAlue :

and I want to use Conditional Operator to setVAlue in another class:

String str = ...
Double dbl = ...
item.setValue((condition) ? str : dbl);

但是编译器说:

cannot find symbol
symbol  : method setValue(java.lang.Object&java.io.Serializable&java.lang.Comparable<? extends java.lang.Object&java.io.Serializable&java.lang.Comparable<?>>)

我认为编译器使用Double和String的最近的通用超类(超级接口)作为条件运算符的类型.但是为什么呢?

I think compiler uses the nearest common superclass (super interface) of Double and String as type of conditional Operator. but why?

推荐答案

因为做其他任何事情都没有任何意义.三元条件运算符必须返回某些特定类型的某个值-所有表达式在编译时必须产生特定类型.此外,请注意,重载解析也发生在编译时.您尝试在此处调用的行为(后期绑定)在Java中不存在此形式.

Because to do anything else wouldn't make any sense. The ternary conditional operator must return some value of some specific type -- all expressions must result in a specific type at compile time. Further, note that overload resolution happens at compile time, as well. The behavior you are trying to invoke here (late binding) doesn't exist in this form in Java.

表达式的类型必须与 true false 子表达式兼容.在这种情况下,最接近的公共祖先类是 Object ,并且您没有 setValue(Object)重载.

The type of the expression must be compatible with the true and false subexpressions. In this case, the nearest common ancestor class is Object, and you don't have a setValue(Object) overload.

这是最有效地重写您拥有的内容的方法:

This is the simplest way to rewrite what you have in a working way:

if (condition) {
    item.setValue(str);
} else {
    item.setValue(dbl);
}

您还可以提供一个 setValue(Object)重载,该重载检查传递的对象的类型并将其委托给适当的 setValue()重载,如果该类型抛出异常是不可接受的.

You could also provide a setValue(Object) overload that inspects the type of object passed and delegates to the appropriate setValue() overload, throwing an exception if the type is not acceptable.

这篇关于Java条件运算符和不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆