Get field values using reflection

rama :

I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

Test.class

import java.lang.reflect.Field;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {

    final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
    field.setAccessible(true);
    field.get(Class.forName("com.logging.EX"));
}

}

EX.class

public class EX {

private String value;


public EX(){
    value="data";
}
/**
 * @return the value
 */
public String getValue() {
    return value;
}

/**
 * @param value
 *            the value to set
 */
public void setValue(String value) {
    this.value = value;
}

}

ManoDestra :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466080&siteId=1
Recommended