Java 中的动态转换
我如何概括以下代码:
String nameString = "myClass_t";
myClass_t myVar = (myClass_t) AnotherClass.classMethod();
AnotherClass.classMethod() 的返回类型需要从文件中获取(因此是一个 String 变量)。 myVar 的类型需要与该类型匹配。
如何重写第二行以使其能够从 nameString 获取类型?
非常感谢您的帮助。
How can I generalize the following code:
String nameString = "myClass_t";
myClass_t myVar = (myClass_t) AnotherClass.classMethod();
The return type of AnotherClass.classMethod() needs to be obtained from a file (thus a String variable).
The type of myVar needs to match that type.
How can I rewrite the 2nd line to enable it to get the type from nameString?
Thank you so much for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这没有多大意义。如果
myVar
的类型不是静态已知的,您将只能通过反射使用它。在这种情况下,只需将其存储为对象
即可。您是否正在尝试验证
classMethod()
是否返回预期类型?或者您是否尝试将结果转换为特定类型,以便可以对其调用特定方法?换句话说,接下来你打算用myVar
做什么?调用类似myVar.myMethod()
的方法?下面是使用反射调用对象方法的示例。参考
类
文档以获得更详细的解释。This doesn't make a lot of sense. If the type of
myVar
is not statically known, you will only be able to use it via reflection. In that case, just store it as anObject
.Are you trying to verify that
classMethod()
is returning the expected type? Or are you trying to cast the result to a specific type so that you can invoke specific methods on it? In other words, what are you going to do withmyVar
next? Invoke a method likemyVar.myMethod()
?Here's an example of invoking a method on an object using reflection. Refer to the
Class
documentation for a more detailed explanation.Class 的实例:
使用 请注意,这可能会引发多个异常,例如,如果字符串定义的类不存在,或者 AnotherClass.classMethod() 未返回要转换为的类的实例。
澄清接口的想法(通常用于 Java 中的插件机制):
基本上你有一个动态类名(例如来自属性文件)。此类实现了一个接口,因此您可以确保类实例提供接口方法(而不是对所有内容都使用反射)。
Use an instance of Class:
Be aware that this might throw several Exceptions, e.g. if the class defined by the string does not exist or if AnotherClass.classMethod() doesn't return an instance of the class you want to cast to.
To clarify the interface idea (which is usally used for plugin mechanisms in Java):
Basically you have a dynamic class name (e.g. from a properties file). This class implements an interface, so you can make sure that class instances provide the interfaces methods (instead of using reflection for everything).