我想在 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/