views:

80

answers:

2

Instead of trying to trying to put my problem into words, here's some code that demonstrates what I want to do:

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++) {
    // Tried the following, but it doesn't work for obvious reasons.
    // It does demonstrate what I want to do.
    comparableObjects[i] = (Comparable) domains[i].cast(stringValues[i]);
}

Any ideas?

+1  A: 

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.

Bozho
+1  A: 

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.

DaveJohnston