使用其值获取接口常量名称
这在项目中可能没有主要用例,但我只是尝试一个 POC 类型的项目,在其中我获取密钥代码,并使用它的值我想在屏幕上打印密钥名称。 我想从写 switch case 中解脱出来,所以考虑通过反思来解决。
有没有办法使用接口名称的值来获取接口名称的常量整数?
KeyPressed(int i) {
string pressedKeyName = getPressedKey(i);
System.out.println(pressedKeyName);
}
This might not have a major usecase in projects, but I was just trying a POC kind of project where in I get the key code, and using its value I want to print the key name on screen.
I want to relive myself off writing switch cases, so thinking of going by reflection.
Is there a way to get the constant integer of interface's name using its value?
KeyPressed(int i) {
string pressedKeyName = getPressedKey(i);
System.out.println(pressedKeyName);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以想到两个比使用反射更好的解决方案。
任何像样的 IDE 都会自动为您填写 switch 语句。我使用 IntelliJ,它会执行此操作(您只需按 ctrl-enter 即可)。我确信 Eclipse/Netbeans 有类似的东西;
但要通过反射找出你想要的内容,假设:
运行:
输出:
I can think of two better solutions to this than using reflection.
Any decent IDE will auto-fill in switch statements for you. I use IntelliJ and it does this (you just press ctrl-enter). I'm sure Eclipse/Netbeans have something similar; and
Enums make a far better choice for constants than public static primitives. The added advantage is they will relieve you of this problem.
But to find out what you want via reflection, assuming:
Run:
Output:
已将其转换为通用方法,以提高可重用性(例如,对于
switch
和default
):Have converted this to a generic method, for improved reusability (eg. for
switch
&default
):