英文:
How can I pass an class datatype as argument and use it for casting
问题
private
System.out.println("Value = " + value);
}
Java Main(){
myFunction(3.214, Float.class);
myFunction(432.13, Integer.class);
}
I'm expecting the output:
3.214
432
But now instead, I got an error. Cannot use classType
for casting.
英文:
How can I solve this issue:
private <T> void myFunction(float value, Class<T> classType){
System.out.println("Value = + (classType) value);
}
Java Main(){
myFunction(3.214, Float.class);
myFunction(432.13, Integer.class);
}
I'm expecting the output:
3.214
432
But now instead, I got error. Cannot use classType
for casting.
答案1
得分: 5
只能将对象引用转换为其祖先类型之一。
例如,在这里,您的对象是Float
类的一个实例。它的祖先是Number和Object类,以及接口Serializable
和Comparable
。这些是您唯一可以转换成的类型。
您不能将对Float
的引用转换为对Integer
的引用,因为Integer
不是Float
的父类。
相反,您可以传递一个函数,该函数将浮点数转换为您希望的任何类型,使用您希望的任何机制。方法声明如下:
private static <T> void myFunction(float value, Function<Float, T> function){
System.out.println("Value = " + function.apply(value));
}
您可以像这样使用它,例如:
myFunction(123.456f, Float::intValue);
英文:
You can cast an object reference to one of its ancestor types only.
For example, here your object is an instance of the Float
class. Its ancestors are the Number and the Object classes, and the interfaces Serializable
and Comparable
. Those are the only types you could cast into.
You cannot cast a reference to Float
to a reference to Integer
because Integer
is not a parent of Float
,
What you could do instead is pass in a function that converts floats to whatever type you want with whatever mechanism you want. The method declaration would look like:
private static <T> void myFunction(float value, Function<Float, T> function){
System.out.println("Value = " + function.apply(value));
}
And you could use it like this for example:
myFunction(123.456f, Float::intValue);
答案2
得分: 1
你可以使用 Class 类的 cast 方法。
就像这样。
private <T> void myFunction(float value, Class<T> classType){
System.out.println("Value = " + classType.cast(value));
}
英文:
You can use the cast-Method of the Class-class.
Like this.
private <T> void myFunction(float value, Class<T> classType){
System.out.println("Value = " + classType.cast(value));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论