2

In the classes I am coding, I tend to have to cast variables to other datatypes quite commonly. I wanted to make a method that could truncate this process. I wanted it to be something like this:

    public static Object typeCast(Object o, DataType type){
    if (o instanceof type){
        return (type) o;
    }else{
        return false;
    }
}

However, I know of no way to save a data type as a variable. Is this possible?

1
  • Look into reflection and Class objects. Commented Mar 16, 2014 at 20:30

2 Answers 2

2

Yes, every DataType is a class which you can get from a object with getClass() at runtime. Saving the Class of a object is quite simple.

Class<Integer> clazz = Integer.class;
Object obj = Integer.valueOf(1);
clazz.instanceOf(obj); // will return true in that case.

You can use also do something like following to cast if possible or return null if not, which works for all classes and object you put in.

public static <T> T typeCast(Object o, Class<T> type) {
    if (type.isInstance(o)) {
        return type.cast(o);
    } else {
        return null;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work either (At least, that I can tell). Might I be calling the method wrong? I am doing this: int x = 5. typeCast(x, long);
Yes, you're doing it wrong. You've to call something like that Integer x = typeCast(obj, Integer.class);. Primitive data types can't be used. Always use the Class representation of them e.g. Integer for int, or Double for double.
0

You will need to use the Class object:

public static Object typeCast(Object o, Class type){
    if (o instanceof type){
        return type.cast(o);
    }else{
        return Boolean.FALSE;
    }
}

where type is the class which you want o to be cast into.

This is not really useful though since you'll get an Object back. Generic methods may help you here but it is not yet clear what are you trying to achieve.

1 Comment

This doesn't compile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.