java - 在 Java 中定义类型转换

标签 java types casting

我想在 Java 中定义从任意类型转换为原始数据类型的类型。是否可以定义从一种任意类型到另一种任意类型的转换?

public class Foo{
    //methods, constructor etc for this class
    ...
    //make it possible to cast an object of type Foo to an integer 
}
//example of how an object of type foo would be cast to an integer
public class Bar(){
    public static void main(String[] args){
        Foo foo1 = new Foo();
        int int1 = (int)foo1;
        System.out.println(int1+"");
    }
}

最佳答案

不能强制转换,但可以提供转换函数:

public class Foo{
    //methods, constructor etc for this class
    ...
    public int toInt(){
        //convert to an int.
    }    
}

然后栏变成:

public class Bar(){
    public static void main(String[] args){
        Foo foo1 = new Foo();
        int int1 = foo1.toInt();
        System.out.println(int1+"");
    }
}

关于java - 在 Java 中定义类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8860343/

相关文章:

java - 使用 java2word api 的 jre 最低版本是多少

c++ - 如何声明 std::vector of boost histograms ? boost 直方图的类型是什么?

Java : How to get Date rather than time?

java - Android应用程序已停止工作-eclipse

Java OkHttp3 只使用 Http/1.1 或 Http/2

c# - 没有 assemblyinfo 的通用类型的全名?

c# - 创建一个有效的数据类型,用于按初始和结果单位 C# 查找转换因子

java - 如何将 map.getValue() 类型转换为 ArrayList<Integer>()?

c++ - 如何将 int* -或- float* 分配给 void* 并稍后使用结果?

c++ - C++ 运算符中的隐式类型转换规则