反射:通过反射加载类中的常量变量

发布于 2024-12-15 10:43:46 字数 215 浏览 1 评论 0原文

我有一个类,其中有一堆常量字符串。

我需要通过反射加载此类并检索这些常量。 我可以达到:

controllerClass = Class.forName(constantsClassName);
Object someclass = controllerClass.newInstance();

但我对如何检索此类中的字段感到困惑。

I have a class which has a bunch of Constant Strings.

I need to load this class via reflection and retrieve those constants.
I can get up to:

controllerClass = Class.forName(constantsClassName);
Object someclass = controllerClass.newInstance();

but I am confused on how to retrieve the fields in this class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

戏舞 2024-12-22 10:43:46

访问字段的快速示例 --

Field[] fields = controllerClass.getDeclaredFields();

for ( Field field : fields ) {
   field.setAccessible(true);
  System.out.println(field.get(someClass));

}

A quick sample on accessing fields --

Field[] fields = controllerClass.getDeclaredFields();

for ( Field field : fields ) {
   field.setAccessible(true);
  System.out.println(field.get(someClass));

}
一生独一 2024-12-22 10:43:46

下面是一个小示例:

import java.lang.reflect.Field;

public class Test {
    public static class X {
        public static int Y = 1;
        private static int Z = 2;

        public int x = 3;
        private int y = 4;
    }

    public static Object getXField(String name, X object) {
        try {
            Field f = X.class.getDeclaredField(name);

            f.setAccessible(true);

            return f.get(object);
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(Test.getXField("Y", null));
        System.out.println(Test.getXField("Z", null));

        System.out.println(Test.getXField("x", new X()));
        System.out.println(Test.getXField("y", new X()));
    }
}

运行这个小程序输出:

1
2
3
4

一些观察结果:

  • 对于静态字段,为 Field.get() 提供的对象可以为 null。 p>

  • 为了简洁起见,我在Exception基类中使用了异常捕获 - 您应该在代码中使用显式异常类。

  • 虽然 Field.get() 通常按预期工作,但 Field.set() 及其朋友却不能说同样的情况。更具体地说,它会很高兴地更改常量的值(例如,final 字段,或在类方法中从未修改的 private 字段),但由于常量内联旧值可能会继续使用。

Here's a little sample:

import java.lang.reflect.Field;

public class Test {
    public static class X {
        public static int Y = 1;
        private static int Z = 2;

        public int x = 3;
        private int y = 4;
    }

    public static Object getXField(String name, X object) {
        try {
            Field f = X.class.getDeclaredField(name);

            f.setAccessible(true);

            return f.get(object);
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(Test.getXField("Y", null));
        System.out.println(Test.getXField("Z", null));

        System.out.println(Test.getXField("x", new X()));
        System.out.println(Test.getXField("y", new X()));
    }
}

Running this little program outputs:

1
2
3
4

A few observations:

  • For static fields the supplied object to Field.get() can be null.

  • For brevity, I used an exception catch-all with the base Exception class - you should use explicit exception classes in your code.

  • While Field.get() usually works as expected, the same cannot be said for Field.set() and its friends. More specifically it will happily change the value of a constant (e.g. a final field, or a private field that is never modified in the class methods), but due to constant inlining the old value may remain in use.

与之呼应 2024-12-22 10:43:46

假设这些常量位于静态字段中:

import java.lang.reflect.*;

public class Reflect {
  public static final String CONSTANT_1 = "1";
  public static final String CONSTANT_2 = "2";
  public static final String CONSTANT_3 = "3";

  public static void main(String[] args) throws Exception {
    Class clazz = Class.forName("Reflect");
    Field[] fields = clazz.getDeclaredFields();
    for(Field f: fields) {
      // for fields that are not visible (e.g. private)
      f.setAccessible(true);

      // note: get(null) for static field
      System.err.printf("%s: %s\n",f, (String)f.get(null) );
    }
  }
}

输出为:

$ java Reflect
public static final java.lang.String Reflect.CONSTANT_1: 1
public static final java.lang.String Reflect.CONSTANT_2: 2
public static final java.lang.String Reflect.CONSTANT_3: 3

请注意 获取静态字段的值,您提供 null 作为参数。

Assuming these constants are in static fields:

import java.lang.reflect.*;

public class Reflect {
  public static final String CONSTANT_1 = "1";
  public static final String CONSTANT_2 = "2";
  public static final String CONSTANT_3 = "3";

  public static void main(String[] args) throws Exception {
    Class clazz = Class.forName("Reflect");
    Field[] fields = clazz.getDeclaredFields();
    for(Field f: fields) {
      // for fields that are not visible (e.g. private)
      f.setAccessible(true);

      // note: get(null) for static field
      System.err.printf("%s: %s\n",f, (String)f.get(null) );
    }
  }
}

The output is:

$ java Reflect
public static final java.lang.String Reflect.CONSTANT_1: 1
public static final java.lang.String Reflect.CONSTANT_2: 2
public static final java.lang.String Reflect.CONSTANT_3: 3

Note that to get the value of a static field, you supply null as the arg.

勿忘初心 2024-12-22 10:43:46

您可以通过类而不是对象引用了解修饰符。

http://download.oracle.com/javase/tutorial/reflect/class /classModifiers.html

You get to know about the modifiers via the class and not the object reference.

http://download.oracle.com/javase/tutorial/reflect/class/classModifiers.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文