从 Class 获取枚举实例扩展枚举>使用字符串值?
我发现很难用语言表达确切的问题,所以我只举一个例子。
我有两种 Enum
类型:
enum Shape {
CAT, DOG;
}
enum Color {
BLUE, RED;
}
我有一个方法:
public Object getInstance(String value, Class<?> type);
我想使用如下方法:
// someValue is probably "RED", and someEnumClass is probably Color.class
Color c = getInstance(someValue, someEnumClass);
我一直无法确定如何实现 getInstance()
。一旦您知道要实例化的确切 Enum
类,就很容易了:
Color.valueOf("RED");
但是如何使用未知的 Class
来完成上面的代码呢? (但是,众所周知,someEnumClass
是 Enum
的子类。)
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该方法将用作:
然后,您始终可以使用
which 的快捷方式
And the method is to be used as:
Then again, you can always use
which is a shortcut for
我们想要获取
Method
对象,该对象反映传入的Class
的valueOf
方法,该方法接受String
> 参数;然后在没有对象(因为它是静态的)和提供的 String 参数的情况下调用
它:您将需要捕获大量不同类型的异常。
We want to get the
Method
object which reflects thevalueOf
method of the passed-inClass
, which accepts aString
parameter; theninvoke
it with no object (since it's static) and the supplied String parameter:You will need to catch a boatload of different types of exceptions.
所以这里是使用 Spring 验证的代码,对我来说非常有用。
完整代码如下。
上述类的实现:
上述注释的用法非常简单
So here is the code being using Spring validation and works great for me.
Full code given below.
Implementation of the above class:
USAGE OF THE ABOVE ANNOTATION IS VERY SIMPLE
由于您知道要查找的类,因此您可以询问枚举是否知道您感兴趣的内容:
但是,将字符串插入多个枚举以寻找合适的值会损害您使用枚举获得的类型安全性。如果您将“红色”映射到
MyColor.RED
和NuclearThreatWarningLevel.RED
那么您至少可能会得到错误的类。在最坏的情况下,你可能会在地下掩体中等待 6 个月,等待空气净化,而你想要的只是一辆漆成红色的汽车:)如果可能的话,最好重新设计代码的这个区域,这样你就不会必须动态地将字符串转换为多个类之一的实例。如果您扩展您的答案以包括您试图解决的问题,也许 SO 社区会有一些想法。
Since you have an idea of what class you're looking for you can just ask the enum if it knows what you're interested in:
However, plugging strings into multiple enums looking for a fit compromises the type safety you get with enums. If you map "red" to both
MyColor.RED
andNuclearThreatWarningLevel.RED
then you may, at the very least, end up with the wrong class. At the worst you could end up in your underground bunker for 6 months waiting for the air to clear, when all you wanted was a car painted red :)It would be better to redesign this area of your code if possible so you don't have to convert a string to an instance of one of several classes dynamically. If you expand your answer to include the problem you're trying to solve perhaps the SO community will have some ideas.