使用反射从字符串构建枚举
我有一个需要枚举的方法。说方法是 methodName(MyTypes) ,其中 MyTypes 位于另一个类中。 数据{ 枚举我的类型{ 编号、值.... } 。
我想动态调用这个方法 要调用它,我必须从输入字符串构建 MyTypes 类型的 emum。例如,输入字符串是 MyTypes.Value。 如何从该字符串动态构建枚举实例并传入方法?
当我执行 method.getGenericParameterType() 时,它会返回类似这样的内容 [class packagename.Data$MyTypes]
使用这两个东西需要泛型类型和字符串值如何构建枚举?
提前致谢。
I have a method which takes an Enum. Say method is methodName(MyTypes) where MyTypes is inside another class. Data{
enum MyTypes{
Id, Value....
}
}
I want to invoke this method dynamically. To call that I have to build an emum of type MyTypes from the input String. The input String is say for example MyTypes.Value.
How to build the enum instance dynamically from this string and pass in the method?
When I am doing method.getGenericParameterType() it returns me something like this
[class packagename.Data$MyTypes]
using this 2 things required generic type and string value how to build the enum?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的意思是?
Do you mean?
类似的事情:解析字符串以获取类名“MyTypes”,然后使用 Class.forName(String) 获取实际的类对象,然后使用 static Enum.valueOf 获取枚举值(类,字符串)
Something like that: parse the string to get the class name "MyTypes", then get the actual class object using
Class.forName(String)
, then get the enum value using staticEnum.valueOf(Class,String)
您想使用反射有什么原因吗?
valueOf
方法还不够吗?看一下 这个。
Is there a reason why you want to use reflection ? Is the
valueOf
method not sufficient ?Take a look at this.
这是我所做的:
Here is what I did: