Java 获取所有类参数&;他们的名字?
我正在寻找能够输入参数名的用户,例如。“sand”,然后我想知道哪个块引用了该名称 参考代码:Java 获取所有类参数&;他们的名字?,java,class,methods,parameters,Java,Class,Methods,Parameters,我正在寻找能够输入参数名的用户,例如。“sand”,然后我想知道哪个块引用了该名称 参考代码: 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
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());
}
}
有几个注意事项:
getDeclaredField
如果提供实际不存在的数据字段的名称,则可以抛出NoSuchFieldException块
实例与问题中显示的一样是静态的,这就是为什么我使用field.get(null)
而不是field.get()
您应该使用反射来访问自动生成的块文件的字段:
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());
}
}
有几个注意事项:
getDeclaredField
如果提供实际不存在的数据字段的名称,则可以抛出NoSuchFieldException块
实例与问题中显示的一样是静态的,这就是为什么我使用field.get(null)
而不是field.get()
反射如果它已生成且无法修改,我认为这可能是您唯一的选择。为什么不作为enum来执行此操作?您是否尝试过将此数据组织在
HashMap
或类似的格式中?嘿,正如我提到的,Blocks.java类是自动生成的,我无法修改它。请使用HashMap
。这正是他们的目的。反思?如果它已生成且无法修改,我认为这可能是您唯一的选择。为什么不作为enum来执行此操作?您是否尝试过将此数据组织在HashMap
或类似的格式中?嘿,正如我提到的,Blocks.java类是自动生成的,我无法修改它。请使用HashMap
。这正是他们的目的。@aze注意到,一般来说,反射是一个可怕的想法。为此,您确实需要找到autogenerator,并提出一个更长期的解决方案。@aze注意,一般来说,反射是一个糟糕的想法。为此,您确实需要找到autogenerator,并提出更长期的解决方案。