Get value of type object - java

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.

Related

How to get a particular value of an object of this example

I have the following code.
private void relacion() throws Exception {
AlumnoDAO alumnodao = new AlumnoDAO();
for (int i = 0; i < alumnodao.listar().size(); i++) {
System.out.println(alumnodao.listar().get(i));
}
}
Which returns me an ArrayList of objects.
But I need access to such name.
You see me back, id, last name etc ..
But I specifically want the name. I am not sure how.
I'm working with POJO
Example:
System.out.println(alumnodao.listar().get(i).id); // access the 'id' field
System.out.println(alumnodao.listar().get(i).nombre); // access the 'nombre' field
System.out.println(alumnodao.listar().get(i).apelidos); // access the 'apelidos' field
You may need to use a getter to access your arraylist's object member variables depending on their visibility.
The get method of ArrayList returns an object, whose public fields can get accessed. For this reason, you can access the name of the returned object by doing the following:
System.out.println(alumnodao.listar().get(i).nombre);
However, in most cases you don't want to have your fields declared as public. What is usually done instead is to have the fields declared as private and access them with getters and setters.

Convert Field Type to the corresponding instance type

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.

Get Thrift Field Type from ID

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

Setting a primitive data type through the use of a Field object

Is there any way to set the value of a primitive through the use of fields? I've tried to play around with the following, but can't seem to get it to work.
temp[i].setInt(new Object(), new Integer(data[0]));
In this case temp would be an array of declared fields. The current index i holds a field that holds a primitive int value. Is this sort of thing even possible?
Assuming you have a Map of field names and values called fieldValues, and you want to set the values on an instance called myObject, this code would check the respective primitive type, then set its value appropriately.
for (String fieldName : fieldValues.keySet())
{
Field field = myObject.getClass().getField(fieldName);
if (field.getType().equals(Integer.TYPE))
{
field.setInt(myObject, Integer.parseInt(fieldValues.get(field.getName());
}
else if (field.getType().equals(Long.TYPE))
{
field.setLong(myObject, Long.parseLong(fieldValues.get(field.getName());
}
else if (field.getType().equals(Boolean.TYPE))
{
field.setBoolean(myObject, Boolean.parseBoolean(fieldValues.get(field.getName());
}
// more else branches for each needed primitive type
}

how to cast string to integer at runtime

I am using reflection in java.
I am getting to know the type of method parameter I am passing at run time. So I am fetching the parameter value from file into a string variable.
SO now if i get to know that the parameter type as integer and if i pass an object containting the string value I am getting
argument type mismatch
java.lang.IllegalArgumentException: argument type mismatch
Class classDefinition = Class.forName("webservices."+objectName);
String methodName = set"+fieldNameAttay[i].substring(0,1)).toUpperCase()+fieldNameAttay[i].substring(1); Field f = classDefinition.getDeclaredField(fieldNameAttay[i]);
try
{
//argType = f.getType();
Method meth = classDefinition.getMethod(methodName,f.getType());
Object arg = new Object[]{fieldValueArray[i]}; //fieldValueArray[i] is always string array
meth.invoke(object, arg); //If f.getType is Integer this //throws ex
}
catch (Exception e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
You can't cast a string to an integer - you can parse it though. For example:
if (parameterType == int.class && argumentType == String.class)
{
int integerArgument = Integer.parseInt((String) argumentValue);
// Now call the method appropriately
}
Of course, you also need to consider Integer as well as int.
How about
Integer.parseInt((String) stringObj)
Note that casting can happen only if the two objects belong in the same hierarchy. So this is not casting.
If the only types you are using are String and Integer, checking the type and then using Integer.parseInt might be the simplest thing to do.
However if you have more different types, I would suggest checking out the good old JavaBeans framwork: http://download.oracle.com/javase/tutorial/javabeans/index.html
And especially the PropertyEditors
http://download.oracle.com/javase/7/docs/api/java/beans/PropertyEditor.html
http://download.oracle.com/javase/7/docs/api/java/beans/PropertyEditorManager.html
The PropertyEditors allow you to set the value as text, and then retrieve the value as correct type. Assuming you have implemented and registered the property editors, the steps to get the correct type are similer to this:
Find out the type of the parameter
Retrieve a PropertyEditor for that type
Use setAsText and getValue in the property editor to convert the value to correct type
...or You can just adapt the same mechanism to your simple needs by implementing your own conversion framework with similar but simpler interfaces.
System.out.println(Integer.parseInt(obj.toString()))
There's another way to do it:
Integer number = Integer.valueOf("1");

Categories