Something like this...
import java.lang.reflect.Field; public class Test { public static void main(String... args) { try { Foobar foobar = new Foobar("Peter"); System.out.println("Name: " + foobar.getName()); Class<?> clazz = Class.forName("com.csa.mdm.Foobar"); System.out.println("Class: " + clazz); Field field = clazz.getDeclaredField("name"); field.setAccessible(true); String value = (String) field.get(foobar); System.out.println("Value: " + value); } catch (Exception e) { e.printStackTrace(); } } } class Foobar { private final String name; public Foobar(String name) { this.name = name; } public String getName() { return this.name; } }
Or, you can use the newInstance method of class to get an instance of your object at runtime. You'll still need to set that instance variable first though, otherwise it won't have any value.
E.g.
Class<?> clazz = Class.forName("com.something.Foobar"); Object object = clazz.newInstance();
Or, where it has two parameters in its constructor, String and int for example...
Class<?> clazz = Class.forName("com.something.Foobar"); Constructor<?> constructor = clazz.getConstructor(String.class, int.class); Object obj = constructor.newInstance("Meaning Of Life", 42);
Or you can interrogate it for its constructors at runtime using clazz.getConstructors()
NB I deliberately omitted the casting of the object created here to the kind expected, as that would defeat the point of the reflection, as you'd already be aware of the class if you do that, which would negate the need for reflection in the first place.
valueis an instance field. Where's your instance ofEX?valuefield, you need an instance ofEXbecausevalueis an instance field. Right now your code attempts to do the equivalent ofcom.logging.EX.class.valuewhich is an error.String value = (String) field.get(foobar);where foobar is an instance of your EX class. And you can instantiate that class at runtime from a Class object and set the value as required.