I need to get the value of a field using reflection. It so happens that I am not always sure what the datatype of the field is. For that, and to avoid some code duplication I have created the following method:
@SuppressWarnings("unchecked") private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable { Field f = classUnderTest.getDeclaredField(processFieldName(var)); f.setAccessible(true); T value = (T) f.get(runtimeInstance); return value; }
And use this method like:
Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
or
Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);
The problem is that I can't seem to cast Integer
to Long
:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
Is there a better way to achieve this?
I am using Java 1.6.
Since int is smaller data type than long, it can be converted to long with a simple assignment. This is known as implicit type casting or type promotion, compiler automatically converts smaller data type to larger data type.
To initialize long you need to append "L" to the end. It can be either uppercase or lowercase. All the numeric values are by default int . Even when you do any operation of byte with any integer, byte is first promoted to int and then any operations are performed.
Yes, you can add a long and an int just fine, and you'll end up with a long . The int undergoes a widening primitive conversion, as described in the Java Language Specification, specifically JLS8, §5.1. 2 .
We can convert String to long in java using Long. parseLong() method.
Simply:
Integer i = 7; Long l = new Long(i);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With