简体   繁体   English

Java隐式转换函数参数

[英]Java implicit cast in function parameters

Is it possible to automatically cast an integer to an object when passing it as function parameter? 将整数作为函数参数传递时,是否可以将整数自动转换为对象? i have this function prototype: 我有这个功能的原型:

public void aggiungiA(Nodo x)

Nodo has his own constructor with an integer parameter. Nodo拥有自己的带有整数参数的构造函数。 Now, What i want do is: 现在,我想做的是:

aggiungiA(5);

with an implicit cast. 使用隐式转换。 is there anyway to do it? 反正有做吗?

There are no implicit casts via constructor invocations in java. 在Java中,没有通过构造函数调用进行隐式强制转换。 You'll have to explicitly call the constructor - either from the caller, or by overloading the method: 您必须显式地调用构造函数-从调用者或通过重载方法:

public class MyClass {
    public void aggiungiA(int i) {
        aggiungiA(new Nodo(i));
    }

    public void aggiungiA(Nodo x) {
        // Do something with X
    }
}

In addition to @Mureinik's answer, I guess you are coming from a C++ background where certain casts do happen automatically. 除了@Mureinik的答案以外,我猜您还来自C ++背景,某些强制转换确实会自动发生。 In Java things are different - the only implisit casts are: 在Java中,情况有所不同-唯一的隐式强制转换为:

  • Widening of numeric types in expressions. 表达式中数字类型的扩展。 For example in long x = myLong + inInt myInt will be cast to a long before the addition of the two long values 例如,在long x = myLong + inIntlong x = myLong + inInt转换为两个long值相加之前的long
  • Primitive values to their object equivelent. 原始值与其对象相等。 For example an 'int' is automatically cast to 'Integer' and a 'boolean' can be automatically cast to a 'Boolean'. 例如,“ int”会自动转换为“ Integer”,而“ boolean”会自动转换为“ Boolean”。 This is called autoboxing 这称为自动装箱
  • Boxed objects can be cast back to their privitive values. 可以将装箱的对象放回其专用值。 For example an 'Integer' can be cast to an 'int' or a 'Character' to a 'char'. 例如,可以将'Integer'强制转换为'int'或将'Character'强制转换为'char'。 As this is the opposite of the previous cast it is called auto unboxing. 由于这与之前的转换相反,因此称为自动拆箱。

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

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