如何通过名称字符串获取枚举值 [英] how can I get enum value by name string

查看:146
本文介绍了如何通过名称字符串获取枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过名称字符串获取枚举值,

I want to get the enum value by name string,

此枚举代码:
包练习;

this the enum code: package practice;

enum Mobile {
  Samsung(400),
  Nokia(250),
  Motorola(325);

  int price;
  Mobile(int p) {
    price = p;
  }
  int showPrice() {
    return price;
  }
}

我可以获得类名和名称字符串

I can get the class name and the name string

Class enumClass = Class.forName("practice.Mobile");
String name = "Samsung";

我如何仅使用enumClass和name获得Samsung值400?
非常感谢

how can I get the Samsung value 400 only use enumClass and name? thanks a lot

推荐答案

您可以使用以下内容:

final Mobile mobile = Mobile.valueOf("Samsung");
final int price = mobile.showPrice();

(您必须更改方法的范围 showPrice() public )。

(you do have to change the scope of the method showPrice() to public).

这篇关于如何通过名称字符串获取枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆