如何使用类在java中获取常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2864612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get a constant in java with class
提问by luxerama
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?
基本上我需要为一个类获取一个常量,但是我没有对象的实例,只有它的类。在 PHP 中我会做constant(XYZ);
在 JAVA 中是否有类似的检索常量的方法?
I need it to facilitate a dynamic getMethod call
我需要它来促进动态 getMethod 调用
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
然后设置属性方法将获得正确的方法并设置指定的属性,但是我无法在不使用 Interger.TYPE 的情况下获得具有 int 作为参数类型的方法
采纳答案by Shervin Asgari
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.
假设您有一个带有属性栏的 Foo 类。
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
现在您将在 bar 变量中获得方法 getBar() 的值
回答by gustafc
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!
回答by AndrejaKo
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.
Final 意味着它一旦设置就无法更改,因此您会得到一个常量。静态意味着即使没有该类的任何对象,它也可以访问。
回答by user85155
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)
你可能会寻找某物。喜欢Foo.class.getDeclaredField("THIS_IS_MY_CONST").get(null);
或
Class.forName("Foo").getDeclaredField("THIS_IS_MY_CONST").get(null);
(感谢foo)
Gets the value of a String constant (THIS_IS_MY_CONST) in class Foo.
获取类 Foo 中字符串常量 (THIS_IS_MY_CONST) 的值。
Update
use null
as argument for get
thanks acdcjunior
更新null
用作get
感谢adcjunior 的参数
回答by Luke Hutchison
If you don't want to actually load or initialize the class, ClassGraphcan do this:
如果您不想实际加载或初始化类,ClassGraph可以这样做:
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.
注意,这仅适用于分配给static final fields 的常量初始化值(可以在没有对象实例化的情况下计算的值,除了String
)。编译器可以在编译时为简单的算术和简单的字符串连接生成一个常量。
(disclaimer, I am the author of ClassGraph)
(免责声明,我是 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
如果您不介意加载类,那么简单地使用反射来访问静态字段会更简单,如其他答案所示:https: //stackoverflow.com/a/4076792/3950982