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

}


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

So basically, this function will take the
limit
value and check if all the values in
columnName
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.

dataset.first().get(columnName).getClass()

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
limit
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