euraad
euraad

Reputation: 2836

How can I pass an class datatype as argument and use it 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.

Upvotes: 0

Views: 73

Answers (2)

vrdrv
vrdrv

Reputation: 313

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));
}

Upvotes: 1

Joni
Joni

Reputation: 111239

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);

Upvotes: 5

Related Questions