Reputation: 574
I have Class type returned by one function and want to cast my object to that type. Below is the code:
Object valueData; //This is holding some data as Object
Class className = getClassFromFunction(); //className = MyValueClass
//Object val = (className.getClass()) valueData;
boolean validate = validate(valueData); //Failing
Here validate function is not accepting the parameter as Object, it will accept as type of the class (className)
boolean validate(MyValueClass req){
}
How do I cast Object to MyValueClass?
Upvotes: 1
Views: 1450
Reputation: 140457
First, you have to understand that casts and deciding which overloaded method to chose ... happens at compile time. In contrast to polymorphism, overloading is decided at compile time.
Therefore, given a fixed, known sets of "target" classes, the following cascading of instanceof
, as ugly as it looks, would work out:
if (someObject instanceof A) {
foo((A) someObject);
return;
}
if (someObject instanceof B) {
foo((B) someObject);
return;
}
Please note: there is no "working around" here using reflection. Reflection kicks in at runtime, and as said, you need all the information at compile time.
If at all, you would have to step back, and see if there are ways of turning your overloading approach into polymorphism.
Upvotes: 1