动态转换:类和字符串进行比较
不要尝试用语言来表达我的问题,这里有一些代码演示了我想要做的事情:
Class cls = Double.class
String str = "31.4";
Comparable comparableObj null;
comparableObj = (Comparable) cls.cast(str);
有什么想法吗?我已经考虑过使用反射但没有成功。
Instead of trying to trying to 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我真的不喜欢你想要做的事情,但这是我对你的代码的修改,以便它编译并运行:
打印:
如果你用文字解释你想要实现的目标,那么它可能会有所帮助,那么你可能会得到更多帮助以更好的方式做到这一点。
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:
Prints:
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.
您必须调用每个类的
valueOf
方法。所以也许:这段代码通过反射获取
valueOf
方法。getMethod(..)
接受方法名称和参数类型,invoke(..)
接受null
作为第一个参数,因为该方法是静态的。如果您想要从字符串转换其他类,则必须使用它们的转换器方法。
但我不知道你是否真的需要这个,以及为什么。因为您知道所有的类和参数。
You would have to invoke the
valueOf
method of each of these classes. So perhaps:This code takes the
valueOf
method by reflection.getMethod(..)
takes the method name and the argument type(s), andinvoke(..)
takesnull
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.