views:

172

answers:

4

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

A: 

I am not sure what you want to get out. But it shouldn't bee 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

Shervin
+1  A: 

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!
gustafc
+1  A: 

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.

AndrejaKo