如何用java获取java中的常量 [英] how to get a constant in java with class
问题描述
基本上我需要为一个类获取一个常量,但是我没有该对象的实例,只有它的类。
在PHP中我会做常量(XYZ);
是否有类似的方法在JAVA中检索常量?
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?
我需要它来促进动态getMethod调用
I need it to facilitate a dynamic getMethod call
Class parameterType = Class.forName(class_name);
object.setProperty(field name, field value, parameterType);
然后set属性方法将获得正确的方法并设置指定的属性,但是我无法获得使用int作为参数类型而不使用Interger.TYPE的方法
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
推荐答案
我不确定你想要什么。但是向你展示一个例子应该不会太难。
I am not sure what you want to get out. But it shouldn't be too difficult to show you an example.
假设你有一个带有属性栏的Class Foo。
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);
现在你将获得bar变量中方法getBar()的值
Now you will get value of method getBar() in bar variable
这篇关于如何用java获取java中的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!