This question already has answers here:
Get field values using reflection
(4 answers)
Closed 3 years ago.
I have following field in a class:
private String str = "xyz";
How do I get the value xyz using the field name only i.e.
I know the name of the field is str and then get the assigned value. Something like:
this.getClass().getDeclaredField("str").getValue();
Currently the Reflection API has field.get(object).
You can use:
String value = (String) this.getClass().getDeclaredField("str").get(this);
Or in a more generalized and safer form:
Field field = anObject.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
String value = (String) field.get(anObject);
And for your example, this should be enough:
String value = this.str;
But you probably know of that one.
Note: anObject.getClass().getDeclaredField() is potentially unsafe as anObject.getClass() will return the actual class of anObject. See this example:
Object anObject = "Some string";
Class<?> clazz = anObject.getClass();
System.out.println(clazz);
Will print:
class java.lang.String
And not:
class java.lang.Object
So for your code's safety (and to avoid nasty errors when your code grows), you should use the actual class of the object you're trying to extract the field from:
Field field = YourObject.class.getDeclaredField(fieldName);
Imagine you have object in variable foo.
Then you need to get Field
Field field = foo.getClass().getDeclaredField("str");
then allow access to private field by:
field.setAccessible(true);
and you can have value by:
Object value = field.get(foo);
Related
My question similar to others but it's little bit more tricky for me
I have a Class DummyData having static defined variables
public static String Survey_1="";
public static String Survey_2="";
public static String Survey_3="";
So, i call them DummyData.Survey_1 and it returns whole string value. Similarly do with DummyData.Survey_2 and DummyData.Survey_3
But the problem is when i call them Dynamically its not return their value.
I have a variable data which value is change dynamically like (data=Survey_1 or data=Survey_2 or data=Survey_3)
I use #Reflection to get its value but failed to get its value
I use methods which I'm mentioning Below help me to sort out this problem.
Field field = DummyData.class.getDeclaredField(data);
String JsonData = field.toString();
and
DummyData.class.getDeclaredField("Survey_1").toString()
but this return package name, class name and string name but not return string value.
What I'm doing can some help me??
Getting the value of a declared field is not as simple as that.
You must first locate the field. Then, you have to get the field from an instance of a class.
Field f = Dummy.class.getDeclaredField(“field”);
Object o = f.get(instanceOfDummy);
String s = (String) o;
Doing the simple toString() of the Field will actually invoke the toString() method of the Field object but won't access the value
You must do something like this:
Field field = SomeClass.class.getDeclaredField("someFieldName");
String someString = (String) field.get(null); // Since the field is static you don't need any instance
Also, beware that using reflection is an expensive and dangerous operation. You should consider redesigning your system
I have a class, in which I have a field called say batman
String batman
And I have method in this class, which does the following:
for(Field field : obj.getClass().getFields()) {
if(field.getName().equals(fieldName)) // here fieldName is batman
//now need to call Strings method like split etc
}
I need to convert the field to String and call methods. Is it possible to do so?
Thanks in advance.
First of all u can use Field batmanField = obj.getClass().getDeclaredField(fieldName); instead foreach. For get field value u can use String batmanValue = batmanField.get(obj);
You can use the Field#get(Object obj) method to get the value of the field represented by the Field you are working with, on the specified object obj.
if (field.getName().equals(fieldName)) {
String batmanValue = (String) field.get(obj);
..
}
This will give you the value of the batman field. Then you can use the String specific methods.
Is there a way to get the type of a parameter using the thrift ID? I have data coming in that needs to go to one of 6 different Thrift objects so I'm using reflection to instantiate the appropriate object and set data fields.
Class<?> cls = Class.forName(package + table.name);
Object o = cls.newInstance();
Method getField = cls.getMethod("fieldForId", int.class);
Object field = getField.invoke(o, thriftId);
Method setField = cls.getMethod("setFieldValue", field.getClass(), Object.class);
setField.invoke(o, field, data);
The variable data is a String. This code works great until it comes across a field with a type other than String where I can get ClassCastException. I tried doing this:
Method getFieldValue = cls.getMethod("getFieldValue", field.getClass());
System.out.println(getFieldValue.invoke(o, field).getClass.getName());
But for String, getFieldValue returns null if they are blank and you can't get the class. I could assume that all null values are Strings, but that seems dangerous considering Lists, Maps, etc are probably returned as null as well.
I also tried getting the Class of the field but it just comes back as the Enum (_Fields) which is expected.
I managed to find a solution. Grab the name of the field then get that field.
Method getFieldName = field.getClass().getMethod("getFieldName");
String fieldName = (String) getFieldName.invoke(field);
Class<?> fieldType = cls.getField(fieldName).getType());
I having type object with fields and I want to get the value of specific field on it ,
how should i do that in java?
here i getting specific field type for field id that are related to entityinstance
and now i want to get the value (like 1,2,3 etc)of this specific field "id".
for (Object entityInstance : fromEntityInstances) {
try {
Field declaredField = entityObj.getDeclaredField("id");
I think you're looking for Field.get:
Object value = declaredField.get(entityInstance);
If you know the type of it, you can then cast. For primitives, there are specific methods, such as Field.getInt()
int id = declaredField.getInt(entityInstance);
Once you get the declared field, you can call its get method, like this:
// Don't forget getType() here ---vvv
Field declaredField = entityObj.getType().getDeclaredField("id");
Object res = declaredField.get(entityInstance);
If all objects there are of the same type, you could move the call of getDeclaredField outside the loop to save yourself some CPU cycles.
I am using reflection to get all methods parameters names.
The problem is when one of the parameters is of type: the.package.myobject [] (array)
String name = method.getParameterTypes()[0].getName()
I get: [the.package.myobject;] //letter L and symbol ;
how can I get pure type name? (without substringing)
You need to check type.isArray() and, if yes, use getComponentType().
final Class<?> c = method.getParameterTypes()[0];
final String name = (c.isArray()? c.getComponentType() : c).getName();
Most likely what you want is
Class firstType = method.getParameterTypes()[0];
// will be null if not an array.
Class firstComponentType = firstType.getComponentType();