如何在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?
基本上,我需要为一个类获得一个常量,但是我没有对象的实例,只有它的类。在PHP中,我使用常量(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
然后,set property方法将获得正确的方法并设置指定的属性,但是,如果不使用Interger.TYPE,则不能获得具有int作为参数类型的方法
4 个解决方案
#1
1
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()的值
更多相关文章
- JAVA中的反射只获取属性的get方法
- 再论javaIO之拷贝MP3(read方法返回int的原因)
- java基础-Arrays类常用方法介绍
- eclipseIDE for Java EE 下 离线 安装CDT的方法
- 在servlet中的init方法得到了对数据库操作的值,怎么传给前端
- 【JAVA】用java编写程序时总提示缺少方法主体或声明抽象的原因
- JAVA 静态方法和静态变量和final和※静态import※
- java如何通过反射 激活静态类的静态方法
- 实现<table>标签的动态新增和后台接受<table>标签的方法