Guillermo Herrera Guillermo Herrera - 2 years ago 57
Java Question

Cast object to unknown data type

I am working on my project where I need to check if a specific value is equal or not to a value on a dataset.

This is the function I'm creating:

public void setSingleLimit(String columnName, Object limit){


is the column of my dataset I will be applying the function to and
is the value used in the equality condition check.

So basically, this function will take the
value and check if all the values in
are equal or not that value.

However, I do not know before hand the type of the column. I can, however, get the data type of the column in the function.


gives me the class of the values in a column (we can safely and securely assume all the values in a column will belong to the same class/data type)

I would like to cast the
object received in the function to the columns class type in order to be able to do a comparison.

I KNOW I can override the function so it can accept different values (int, long, Boolean, String, etc.) and that will certainly work. However, I want to create a single method for less complexity and for easy understanding to my end user. We can also securely assume that the user will enter a correct value on the function, meaning that if the column is a column of Strings, the user will NOT put a value that is not a String.

Any idea of how I can cast an object to a class that is not known before hand?

Thank you.

Answer Source

You say you want to check for equality. Just use equals(Object o). It is declared on Object and accepts an Object as parameter. The implementation will be bound dynamically at runtime.

public void setSingleLimit(String columnName, Object limit){
    Object columnValue = getValue(columnName);
    limit.equals(columnValue); // If limit can be null, swap variables

Example: If limit is a String, equals() from String will be used. It doesn't matter if columnValue is not a String because it will just return false in that case.

Just make sure the different equals() implmentations do what you want. If you use custom classes you can overwrite it yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download