10

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

}

6
  • 2
    value is an instance field. Where's your instance of EX? Commented Jun 6, 2017 at 17:06
  • I am trying to get the object of EX at runtime. Commented Jun 6, 2017 at 17:09
  • 1
    Well, to get the value field, you need an instance of EX because value is an instance field. Right now your code attempts to do the equivalent of com.logging.EX.class.value which is an error. Commented Jun 6, 2017 at 17:11
  • Is there any way to get the value at runtime. I tried a lot but not seem to get anywhere.Thanks Commented Jun 6, 2017 at 17:13
  • 2
    You need to have an instance of the class to access that field. Otherwise, it's meaningless. 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. Commented Jun 6, 2017 at 17:14

4 Answers 4

16

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi MadoDestra ,Sorry I updated my question.What I am trying to do is get the obejct at runtime. I do not know what the object name is.
You would still have to know the object type to be able to instantiate it. Or if it's a vague object, then you can call getClass() to determine its class. Or you can use instanceof, but I would not recommend this approach.
I have detailed above how to get an instance of your object at runtime. Either by using the constructor or calling newInstance() on the class object itself, but you need to know its fully qualified path name as a string first.
@rama Added some additional info on instantiation of objects at runtime.
2

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

Comments

2

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!

Comments

1

You need the EX isntance on field.get().

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.