gpt4 book ai didi

java - 获取所有类参数及其名称?

转载 作者:行者123 更新时间:2023-12-02 01:04:58 27 4
gpt4 key购买 nike

我正在寻找能够输入参数名称的用户,例如。 “sand”,然后我想知道哪个 block 引用了该名称。

引用代码:

public class Blocks implements ContentList {
public static Block air;
public static Block spawn;
public static Block deepwater;
public static Block water;
public static Block taintedWater;
public static Block tar;
public static Block stone;
public static Block craters;
public static Block charr;
public static Block sand;
public static Block darksand;
public static Block ice;
public static Block snow;
public static Block darksandTaintedWater;
public static Block holostone;
public static Block rocks;
}

我的尝试:

String targetBlock = ctx.args[2].toLowerCase();
Block desiredBlock = Blocks.copperWall;
for(Block block : Blocks.all()){
if (block.name == targetBlock){
desiredBlock = block;
}
}

显然不行,因为Blocks.java没有.all()方法另外,Blocks.java 是自动生成的,我无法修改它或添加方法,有什么想法吗?

最佳答案

您应该使用反射来访问自动生成的 Blocks 文件的字段:

import java.lang.reflect.Field;

class Block {

private String name;
public Block(String name) {
this.name = name;
}

public String getName() {
return name;
}
}
class Blocks {

public static Block wall = new Block("wall");
public static Block corner = new Block("corner");
......
}

public class Main {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Field field = Blocks.class.getDeclaredField("wall"); // get the value from the args in real program
Block b = (Block)field.get(null);
System.out.println(b.getName());
}
}

一些注意事项:

  1. getDeclaredField如果您提供实际上不存在的数据字段的名称,则可以抛出 NoSuchFieldException
  2. 我假设生成的 Block正如问题中出现的那样,实例是静态的,这就是我使用 field.get(null) 的原因而不是field.get(<something of type Blocks>)

关于java - 获取所有类参数及其名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60176094/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com