Java 如何在使用反射时访问实例?
我有一个类在运行时通过实例的成员循环 下面是一个包含不同类型的不同字段的类。AssetTexture是我想要循环使用的类型之一Java 如何在使用反射时访问实例?,java,Java,我有一个类在运行时通过实例的成员循环 下面是一个包含不同类型的不同字段的类。AssetTexture是我想要循环使用的类型之一 public class A { public static AssetTexture T_BG = new AssetTexture("bg.png"); public static AssetTexture T_REELS = new AssetTexture("reels.png"); public stat
public class A {
public static AssetTexture T_BG = new AssetTexture("bg.png");
public static AssetTexture T_REELS = new AssetTexture("reels.png");
public static AssetTexture T_LOGO = new AssetTexture("logo.png");
public static String things_that_should_not_inside_the_loop;
}
下面是AssetTexture类的示例代码。它只包含一个名称
class AssetTexture {
private String name;
public AssetTexture(String name){
this.name=name;
}
}
下面是我在运行时循环遍历所有字段的方法。这是成功的。但我已经尝试了所有可用的现场方法。它没有获取成员的方法
public class Manager {
public Manager(){
A a=new A();//init A
//loop through all field of instance a
Field[] fields=this.a.getClass().getDeclaredFields();
for(Field field:fields){
if(field.getType().equals(AssetTexture.class)){
Gdx.app.debug("Debug", field.getName());
}
}
}
电流输出:
T_BG
T_LOGO
T_REELS
预期结果:
bg.png
reels.png
logo.png
我已经尝试使用toString方法并在AssetTexture中覆盖toString。就像下面的代码一样
field.getName() ---> field.toString()
已重写AssetTexture中的toString
class AssetTexture {
@Override
public String toString() {return name;}
}
但它不运行覆盖方法 不要调用
field.getName()
,而是调用field.get(null).toString()
Field.get
返回特定实例的字段值,对于静态字段,不需要该实例,因此可以传递null。调用Field.getName()
,而不是调用Field.get(null).toString()
Field.get
返回特定实例的字段值,对于静态字段,该实例不是必需的,因此可以传递null。现在您收到了字段名。使用“(字符串)字段。获取(a)”。现在看到您正在接收字段名。使用“(字符串)字段。获取(a)”。看见