Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get field values using reflection

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;
}

}

like image 253
rama Avatar asked Jun 06 '17 17:06

rama


3 Answers

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.

like image 165
ManoDestra Avatar answered Nov 09 '22 12:11

ManoDestra


You can create instance from class object and that can be used in field get value.

 Class modelClass = Class.forName("com.gati.stackoverflow.EX");
    final Field field = modelClass.getDeclaredField("value");
    field.setAccessible(true);
    Object modelInstance=modelClass.newInstance();
    field.get(modelInstance);
like image 44
gati sahu Avatar answered Nov 09 '22 11:11

gati sahu


So, have got the below answer. It is working fine for now. Not sure whether this is the best one to follow.

Your Test class :

public class Test {

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

        Field[] fields = Class.forName("com.logging.EX").newInstance().getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            System.out.println(field.getName() + " : " + field.get(Class.forName("com.logging.EX").newInstance()));
        }

    }
}

I'm extracting all the fields in to an array by invoking the instance of com.logging.EX and then loops through all the fields and extracts the name and the value the field holds. Haven't hardcoded any field name here.

There are few security caveats with mine as I've accessed the variable with private access modifier but that always exists with reflection. Just a disclaimer!

Hope this helps!

like image 45
harshavmb Avatar answered Nov 09 '22 11:11

harshavmb