Get Thrift Field Type from ID - java

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

Related

How to access dynamiclly variables from another Java Class?

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

Reflection and runtime class to get method

Actually in all my class, i alway have attribute name
Class clazz, Object obj
When we know the object type, we can do something like (if id is a attribute....)
Integer id = ((BaseObj) field.get(obj)).getId();
Actually
field.get(obj))
return me a object, i search to get value of name attribute of this object.
I search to do something like
String name = ((clazz.getClass()) field.get(obj)).getName();
You cannot cast to a class that's only known at runtime. Either make all these classes implement an interface with a getName() method or you'll have to resort to reflection:
String name = (String) clazz.getMethod("getName").invoke(obj);

Java Reflection: Casting an Object to another without knowing their types

I am using reflections to map an ResultSet to a Field in bean.
field = clazz.getDeclaredField(str);
field.setAccessible(true);
Object resultSetObject = rs.getObject(str);
Class fieldType = field.getType();
field.set(clazzInst, fieldType.cast(resultSetObject));
The problem is resultSetObject is of type Integer and fieldType is of Long and I cannot cast Intger to Long and getting ClassCastException.
You are essentially asking to duplicate the type knowledge that is available at compile-time with which the compiler generates the correct conversion. The runtime doesn't have this knowledge, so you will have to provide it by building a matrix of types and coding all the conversions you want, explicitly.
You can define this as a matrix indexed by type along both axes (from-type and to-type) or more likely as a Map whose key is a ConversionType object each instance of which defines fromType, toType and a convert() method.
Whether you have
Object ref = new String("object of type string");
or
String ref = new String("still object of type string");
the object referenced will be of type String. Doing
Object obj = (Object) new String("still a string");
does not change that the referenced object is a String. In your case, you'll probably need a conversion strategy to convert between types.
You still have another option, convert long to string ,and then convert to integer.

Get value of type object

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.

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