So this is the code which makes me sad :
private static void AssignId(object entity, string id)
{
var idFieldInfo = entity.GetType().GetProperties().SingleOrDefault(it => it.GetCustomAttributes(typeof(KeyAttribute), false).Any());
if (idFieldInfo != null)
{
var type = idFieldInfo.PropertyType;
if (type == typeof(byte))
{
idFieldInfo.SetValue(entity, Convert.ToByte(id), null);
}
else if (type == typeof(short))
{
idFieldInfo.SetValue(entity, Convert.ToInt16(id), null);
}
else if (type == typeof(int))
{
idFieldInfo.SetValue(entity, Convert.ToInt32(id), null);
}
else if (type == typeof(long))
{
idFieldInfo.SetValue(entity, Convert.ToInt64(id), null);
}
else if (type == typeof(sbyte))
{
idFieldInfo.SetValue(entity, Convert.ToSByte(id), null);
}
else if (type == typeof(ushort))
{
idFieldInfo.SetValue(entity, Convert.ToUInt16(id), null);
}
else if (type == typeof(uint))
{
idFieldInfo.SetValue(entity, Convert.ToUInt32(id), null);
}
else if (type == typeof(ulong))
{
idFieldInfo.SetValue(entity, Convert.ToUInt64(id), null);
}
}
}
Is there a smarter way to assign a string value corresponding integer
Set Field Value With Reflection 1 Overview. In our previous article, we discussed how we could read the values of private fields from a different class in Java. 2 Setting Primitive Fields. We can set the fields that are primitives by using the Field#setXxx methods. 3 Setting Fields That Are Objects 4 Exceptions. ... 5 Conclusion. ...
Next, we will consider how to convert a string to an integer using the Integer.valueOf () method. 2. Use Integer.valueOf () to Convert a String to an Integer. This method returns the string as an integer object. If you look at the Java documentation, Integer.valueOf () returns an integer object which is equivalent to a new Integer ...
Setting Integer Fields We can use the setByte, setShort, s etInt, and setLong methods to set the byte, short, int, and long fields, respectively: 2.2. Setting Floating Type Fields
It's worth reading Oracle Java Tutorial - Getting and Setting Field Values Field#set(Object object, Object value)sets the field represented by this Fieldobject on the specified objectargument to the specified new value. It should be like this f.set(objectOfTheClass, new ConcurrentHashMap<>());
You can use Convert.ChangeType
if (idFieldInfo != null)
{
var type = idFieldInfo.PropertyType;
idFieldInfo.SetValue(entity, Convert.ChangeType(id, type), null);
}
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