diff --git a/src/main/java/org/jenkinsci/plugins/envinject/service/EnvInjectMasterEnvVarsSetter.java b/src/main/java/org/jenkinsci/plugins/envinject/service/EnvInjectMasterEnvVarsSetter.java index 1b6067e1..6e883640 100644 --- a/src/main/java/org/jenkinsci/plugins/envinject/service/EnvInjectMasterEnvVarsSetter.java +++ b/src/main/java/org/jenkinsci/plugins/envinject/service/EnvInjectMasterEnvVarsSetter.java @@ -7,7 +7,10 @@ import org.jenkinsci.lib.envinject.EnvInjectException; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; + import edu.umd.cs.findbugs.annotations.NonNull; /** @@ -21,6 +24,23 @@ public EnvInjectMasterEnvVarsSetter(@NonNull EnvVars enVars) { this.enVars = enVars; } + private Field getModifiers() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { + Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class); + getDeclaredFields0.setAccessible(true); + Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false); + Field modifiers = null; + for (Field each : fields) { + if ("modifiers".equals(each.getName())) { + modifiers = each; + break; + } + } + if (modifiers == null) { + throw new NoSuchFieldException(); + } + return modifiers; + } + @Override public Void call() throws EnvInjectException { try { @@ -32,14 +52,14 @@ public Void call() throws EnvInjectException { } Field masterEnvVarsFiled = EnvVars.class.getDeclaredField("masterEnvVars"); masterEnvVarsFiled.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); + Field modifiersField = getModifiers(); modifiersField.setAccessible(true); modifiersField.setInt(masterEnvVarsFiled, masterEnvVarsFiled.getModifiers() & ~Modifier.FINAL); masterEnvVarsFiled.set(null, enVars); - } catch (IllegalAccessException iae) { + } catch (IllegalAccessException | NoSuchFieldException iae) { throw new EnvInjectException(iae); - } catch (NoSuchFieldException nsfe) { - throw new EnvInjectException(nsfe); + } catch (InvocationTargetException | NoSuchMethodException e) { + throw new RuntimeException(e); } return null;