简体   繁体   English

(JAVA/KOTLIN) 我可以“转换”字符串以调用现有变量吗? 像“varname”.getvariable?

[英](JAVA/KOTLIN) Can I “convert” a string to call an existing variable? like “varname”.getvariable?

Can I use a string to call an existing variable or object by name?我可以使用字符串按名称调用现有变量或 object 吗? The question is kind of abstract but I'm looking for something like this.这个问题有点抽象,但我正在寻找这样的东西。

Example例子

var number = 5

var getnumber = "number"

if (getnumber.(???) > 10)
{...}

or 

if ("number".(???) > 10)

{...}```

This is impossible: At the class level, local variable names do not exist at all.这是不可能的:在 class 级别,根本不存在局部变量名称。

The usual solution is to stop thinking 'python' or 'javascript', where each object is a kind of HashMap<String, Object> , and think java.通常的解决方案是停止思考“python”或“javascript”,其中每个 object 都是一种HashMap<String, Object> ,而思考 java。

If you just can't get your head out of python/javascript space, or the problem fundamentally boils down to this idea, well, you have your answer:如果你只是无法摆脱 python/javascript 空间,或者问题从根本上归结为这个想法,那么,你有你的答案:

Make a Map<String, Object> instead of a local variable:制作Map<String, Object>而不是局部变量:

Map<String, Integer> map = new HashMap<>();
map.put("number", 5);
var getNumber = "number";
if (map.get(getNumber) > 10) { .... }

In case you have a fixed amount of entries, you might use an enum:如果您有固定数量的条目,您可以使用枚举:

private enum class Size(val cm: Int) {
    SMALL(50),
    MEDIUM(100),
    LARGE(150),
}

Usage could be like:用法可能像:

val sizeOne = Size.MEDIUM
val sizeTwo = Size.LARGE

if(sizeOne.cm > sizeTwo.cm ) { ... }

val sizeHundred = Size.values().find { it.cm == 100 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM