如何通过类获取java中的常量

发布于 2024-09-02 06:00:07 字数 342 浏览 7 评论 0原文

基本上我需要获取一个类的常量,但是我没有该对象的实例,只有它的类。 在 PHP 中我会做 constant(XYZ); JAVA中是否有类似的方法来检索常量?

我需要它来促进动态 getMethod 调用,

Class parameterType = Class.forName(class_name);
object.setProperty(field name, field value, parameterType);

然后设置属性方法将获取正确的方法并设置指定的属性,但是如果不使用 Interger.TYPE,我无法获取以 int 作为参数类型的方法

basically I need to get a constant for a class however I have no instance of the object but only its class.
In PHP I would do constant(XYZ);
Is there a similar way of retrieving a constant in JAVA?

I need it to facilitate a dynamic getMethod call

Class parameterType = Class.forName(class_name);
object.setProperty(field name, field value, parameterType);

the set property method would then get the correct method and set the specified property, however I cant get a method which has int as parameter type without using Interger.TYPE

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

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

发布评论

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

评论(6

故人的歌 2024-09-09 06:00:07

你可能会寻找某物。就像
<代码>
Foo.class.getDeclaredField("THIS_IS_MY_CONST").get(null);

或者
<代码>
Class.forName("Foo").getDeclaredField("THIS_IS_MY_CONST").get(null);

(感谢 foo

获取 Foo 类中的字符串常量 (THIS_IS_MY_CONST) 的值。

更新
使用 null 作为 get 的参数,谢谢 acdcjunior

You might look for sth. like

Foo.class.getDeclaredField("THIS_IS_MY_CONST").get(null);

or

Class.forName("Foo").getDeclaredField("THIS_IS_MY_CONST").get(null);

(thanks f-o-o)

Gets the value of a String constant (THIS_IS_MY_CONST) in class Foo.

Update
use null as argument for get thanks acdcjunior

一抹苦笑 2024-09-09 06:00:07

我不确定你想得到什么。但向您展示一个例子应该不会太困难。

假设您有一个带有属性栏的 Foo 类。

Class Foo {
    private final String bar = "test";
    public String getBar() {return bar;}
}

现在,要通过反射获得此值,您将:

Class fooClass = Foo.class;
Object fooObj = fooClass.newInstance();
Method fooMethod = fooClass.getMethod("getBar");
String bar = (String) fooMethod.invoke(fooObj);

现在您将在 bar 变量中获取方法 getBar() 的值

I am not sure what you want to get out. But it shouldn't be too difficult to show you an example.

Lets say you have a Class Foo with property bar.

Class Foo {
    private final String bar = "test";
    public String getBar() {return bar;}
}

Now to get this through reflection you would:

Class fooClass = Foo.class;
Object fooObj = fooClass.newInstance();
Method fooMethod = fooClass.getMethod("getBar");
String bar = (String) fooMethod.invoke(fooObj);

Now you will get value of method getBar() in bar variable

记忆之渊 2024-09-09 06:00:07

如果这个常量是关于类的元数据,我会使用 注释

第一步,声明注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Abc {
    String value(); 
}

第二步,注释您的类:

@Abc("Hello, annotations!")
class Zomg {

}

第三步,检索值:

String className = "com.example.Zomg";
Class<?> klass = Class.forName(className);
Abc annotation = klass.getAnnotation(Abc.class);
String abcValue = annotation.value();
System.out.printf("Abc annotation value for class %s: %s%n", className, abcValue);

输出为:

Abc annotation value: Hello, annotations!

If this constant is metadata about the class, I'd do this with annotations:

First step, declare the annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Abc {
    String value(); 
}

Step two, annotate your class:

@Abc("Hello, annotations!")
class Zomg {

}

Step three, retrieve the value:

String className = "com.example.Zomg";
Class<?> klass = Class.forName(className);
Abc annotation = klass.getAnnotation(Abc.class);
String abcValue = annotation.value();
System.out.printf("Abc annotation value for class %s: %s%n", className, abcValue);

Output is:

Abc annotation value: Hello, annotations!
美煞众生 2024-09-09 06:00:07

要获得私有常量,例如:

private static final String BAR = "test";

您需要首先将其设置为可访问:

Field barField = Foo.class.getDeclaredField("BAR");
barField.setAccessible(true);
String bar = (String) barField.get(null);

To get private constant like:

private static final String BAR = "test";

you need to set it accessible first:

Field barField = Foo.class.getDeclaredField("BAR");
barField.setAccessible(true);
String bar = (String) barField.get(null);
巡山小妖精 2024-09-09 06:00:07

也许我不明白你需要什么,但是你尝试过使用最终静态属性和静态方法吗?

Final 意味着一旦设置就无法更改,因此您得到一个常量。
静态意味着即使没有该类的任何对象,它也可以访问。

Maybe I don't understand what you need, but did you try with final static attributes and static methods?

Final means that it can't be changed once set, so you get a constant.
Static means it's accessible even if there aren't any objects of the class.

离不开的别离 2024-09-09 06:00:07

如果您不想实际加载或初始化类, ClassGraph 可以这样做:

String fieldVal;
try (ScanResult scanResult =
        new ClassGraph().whitelistClasses(className).enableFieldInfo().scan()) {
    fieldVal = (String) scanResult.getClassInfo(className).getFieldInfo("s")
            .getConstantInitializerValue();
}

注意这一点仅适用于分配给静态最终字段的常量初始值设定项(无需对象实例化即可计算的值,String 除外)。编译器可以在编译时生成一个常量,用于简单的算术和简单的字符串连接。

(免责声明,我是 ClassGraph 的作者)

如果您不介意加载类,那么简单地使用反射来访问静态字段会更简单,如另一个答案中所示: https://stackoverflow.com/a/4076792/3950982

If you don't want to actually load or initialize the class, ClassGraph can do this:

String fieldVal;
try (ScanResult scanResult =
        new ClassGraph().whitelistClasses(className).enableFieldInfo().scan()) {
    fieldVal = (String) scanResult.getClassInfo(className).getFieldInfo("s")
            .getConstantInitializerValue();
}

N.B. this works only for constant initializer values (values that can be computed without object instantiation, with the exception of String), assigned to static final fields. The compiler can produce a constant at compiletime for simple arithmetic and simple string concatenation.

(disclaimer, I am the author of ClassGraph)

Simply using reflection to access static fields is simpler, if you don't mind loading the class, as given in this other answer: https://stackoverflow.com/a/4076792/3950982

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