Consider the code:
Number n=new Integer(20);
cast(n) //return's n casted to Integer
<T> T cast(Number num)//to cast from abstract to concrete implemenation
{
// Get which implementation of Number this by calling num.getClass()
//cast to Specific implementation and return
}
Is the above code possible ? Can casting be done when I'm not sure what the implementation is ? If so how should the above function be implemented ?
Due to erasure, T
will be compiled to Object
and the result will be an (Object)
cast anyway.
(I've seen a similar question here on SO with a more elaborate explanation. Can't find it now though.)
This compiles however. I can't see how it would be useful though, but perhaps you can :)
class Main {
public static void main(String[] args) {
Number n = new Integer(20);
Integer i = cast(n); //return's n casted to Integer
}
static <T> T cast(Number num) {
return (T) num;
}
}
Casting is impacting on the type of the object not on the object.
so your method
cast(n)
will do nothing
The best option is to do this:
<T extends Number> T cast(Number num) {
return (T) num;
}
Or, better approach, it's a bit dirty but you get the point....
/**
* @author The Elite Gentleman
*
*/
public class Test {
/**
*
*/
public Test() {
// TODO Auto-generated constructor stub
Number n = new Integer(20);
Double t = cast(n, Double.class);
System.out.println(t);
}
@SuppressWarnings("unchecked")
public <T extends Number> T cast(Number num, Class<T> clazz) {
if (num instanceof Integer) {
return specificCast(num.intValue(), clazz);
}
// if (num instanceof Double) {
// return specificCast(num.doubleValue(), clazz);
// }
return (T) num;
}
@SuppressWarnings("unchecked")
private <T extends Number> T specificCast(int value, Class<T> clazz) {
if (clazz != null) {
if (clazz == Float.class) {
return (T)Float.valueOf((float)value);
}
if (clazz == Double.class) {
return (T)Double.valueOf((double)value);
}
if (clazz == Long.class) {
return (T)Long.valueOf((long)value);
}
if (clazz == Short.class) {
return (T)Short.valueOf((short)value);
}
if (clazz == Integer.class) {
return (T)Integer.valueOf(value);
}
}
return null;
}
public static void main(String[] args) {
new Test();
}
}
Output...
20.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.