Fix some conversion problems
All checks were successful
Build / build (push) Successful in 1m31s

This commit is contained in:
2025-06-10 13:30:36 +02:00
parent d702544f2c
commit 698f6a3903
2 changed files with 67 additions and 1 deletions

View File

@@ -99,7 +99,7 @@ public class AssetProperty {
.setter((obj, value) -> { .setter((obj, value) -> {
try { try {
property.setAccessible(true); property.setAccessible(true);
property.set(obj, value); property.set(obj, Converters.convert(value, property.getType()));
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@@ -0,0 +1,66 @@
package be.seeseepuff.pcinv.meta;
import lombok.experimental.UtilityClass;
/**
* Utility class for converting values to different types.
*/
@UtilityClass
public class Converters {
/**
* Converts a value to the specified target type.
*
* @param value The value to convert.
* @param target The target class to convert the value to.
* @return The converted value, or null if conversion is not possible.
*/
public static Object convert(Object value, Class<?> target) {
if (value == null) {
return null;
}
if (target.isInstance(value)) {
return value; // No conversion needed
}
if (value instanceof Long longValue) {
return convertLong(longValue, target);
}
if (value instanceof Integer intValue) {
return convertInteger(intValue, target);
}
throw new ClassCastException("Cannot convert " + value.getClass().getName() + " to " + target.getName());
}
/**
* Converts a Long value to the specified target type.
*
* @param value The Long value to convert.
* @param target The target class to convert the value to.
* @return The converted value, or throws ClassCastException if conversion is not possible.
*/
private static Object convertLong(Long value, Class<?> target) {
if (target == Long.class || target == long.class) {
return value; // No conversion needed
}
if (target == Integer.class || target == int.class) {
return value.intValue();
}
throw new ClassCastException("Cannot convert " + value.getClass().getName() + " to " + target.getName());
}
/**
* Converts an Integer value to the specified target type.
*
* @param value The Integer value to convert.
* @param target The target class to convert the value to.
* @return The converted value, or throws ClassCastException if conversion is not possible.
*/
private static Object convertInteger(Integer value, Class<?> target) {
if (target == Integer.class || target == int.class) {
return value; // No conversion needed
}
if (target == Long.class || target == long.class) {
return value.longValue();
}
throw new ClassCastException("Cannot convert " + value.getClass().getName() + " to " + target.getName());
}
}