你可以将一个类数据类型作为参数传递,并用它进行类型转换。

huangapple go评论75阅读模式
英文:

How can I pass an class datatype as argument and use it for casting

问题

private void myFunction(float value, Class classType){
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类,以及接口SerializableComparable。这些是您唯一可以转换成的类型。

您不能将对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 &lt;T&gt; void myFunction(float value, Function&lt;Float, T&gt; function){
    System.out.println(&quot;Value = &quot; + 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 &lt;T&gt; void myFunction(float value, Class&lt;T&gt; classType){
    System.out.println(&quot;Value = &quot; + classType.cast(value));
}

huangapple
  • 本文由 发表于 2020年7月31日 22:00:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63193292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定