开发者

Dynamic Cast: Class and String to Comparable

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜