Instead of trying to trying t开发者_如何学Goo put my problem into words, here's some code that demonstrates what I want to do:
Class cls = Double.class
String str = "31.4";
Comparable comparableObj null;
comparableObj = (Comparable) cls.cast(str);
Any ideas? I've looked at using reflection but with no success.
I really don't like what you are trying to do, but here is my modification of your code so that it compiles and runs:
Class [] domains = { Integer.class, Double.class, String.class };
String [] stringValues = { "12", "31.4", "dog" };
Comparable [] comparableObjects = { null, null, null };
for (int i = 0; i < domains.length; i++) {
Constructor con = domains[i].getConstructor(String.class);
comparableObjects[i] = (Comparable) con.newInstance(stringValues[i]);
System.out.println(comparableObjects[i]);
}
Prints:
12
31.4
dog
It might help though if you explain in words what you are trying to achieve, then you might get more help doing it a better way.
You would have to invoke the valueOf
method of each of these classes. So perhaps:
for (int i = 0; i < domains.length; i++) {
try {
comparableObjects[i] = (Comparable) domains[i]
.getMethod("valueOf", String.class).invoke(null, stringValues[i]);
} catch (NoSuchMethodException ex) {
comparableObjects[i] = stringValues[i];
}
}
This code takes the valueOf
method by reflection. getMethod(..)
takes the method name and the argument type(s), and invoke(..)
takes null
as first argument, because the method is static.
If there are other classes that you want to convert from String, you'd have to use their converter methods.
But I don't know whether you actually need this, and why. Since you know all the classes and arguments.
精彩评论