vendredi 21 mai 2021

Replacement for sun.reflect.ConstructorAccessor

I am trying to mavenize some old code and I found these two imports:

import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;

Used in this code:

ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory();

private static void setFailsafeFieldValue(Field inField, Object inTarget, Object inValue) throws NoSuchFieldException, IllegalAccessException {

    // let's make the field accessible
    inField.setAccessible(true);

    // next we change the modifier in the Field instance to
    // not be final anymore, thus tricking reflection into
    // letting us modify the static final field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    int modifiers = modifiersField.getInt(inField);

    // blank out the final bit in the modifiers int
    modifiers &= ~Modifier.FINAL;
    modifiersField.setInt(inField, modifiers);

    FieldAccessor fa = reflectionFactory.newFieldAccessor(inField, false);
    fa.set(inTarget, inValue);
}

private static ConstructorAccessor getConstructorAccessor(Class<?> inEnumClass, Class<?>[] inAdditionalParameterTypes) throws NoSuchMethodException {
    Class<?>[] parameterTypes = new Class[inAdditionalParameterTypes.length + 2];
    parameterTypes[0] = String.class;
    parameterTypes[1] = int.class;
    System.arraycopy(inAdditionalParameterTypes, 0, parameterTypes, 2, inAdditionalParameterTypes.length);
    return reflectionFactory.newConstructorAccessor(inEnumClass.getDeclaredConstructor(parameterTypes));
}

Since this is a sun.* class and we should not use it, is there a replacement for it? I can't seem to find anything.





Aucun commentaire:

Enregistrer un commentaire