i would like to do dynamic casting for a java variable, the casting type is stored in a different variable.
this is regular casting:
String a = (String) 5;
this is what i want:
String theType = 'String';
String a = (theType) 5;
is it possible? and if so how? thanks!
update
I'm trying to populate a class with a hashMap that i received.
this is the constructor:
public ConnectParams(HashMap obj) {
for (Map.Entry entry : obj.entrySet()) {
try {
Field f = this.getClass().getField(entry.getKey());
f.set(this, entry.getValue()); /* <= CASTING PROBLEM */
} catch (NoSuchFieldException ex) {
log.error("did not find field '" + entry.getKey() + '"');
} catch (IllegalAccessException ex) {
log.error(ex.getMessage());
}
}
}
the problem here is that some of the classes variables are Double type, and if the number 3 is received it sees it as Integer and i have type problem.
解决方案
Regarding your update, the only way to solve this in Java is to write code that covers all cases with lots of if and else and instanceof expressions. What you attempt to do looks as if are used to program with dynamic languages. In static languages, what you attempt to do is almost impossible and one would probably choose a totally different approach for what you attempt to do. Static languages are just not as flexible as dynamic ones :)
Good examples of Java best practice are the answer by BalusC (ie ObjectConverter) and the answer by Andreas_D (ie Adapter) below.
That does not make sense, in
String a = (theType) 5;
the type of a is statically bound to be String so it does not make any sense to have a dynamic cast to this static type.
PS: The first line of your example could be written as Class stringClass = String.class; but still, you cannot use stringClass to cast variables.