|
| 1 | +package scala.runtime; |
| 2 | + |
| 3 | +import java.io.Serializable; |
| 4 | +import java.security.AccessController; |
| 5 | +import java.security.PrivilegedActionException; |
| 6 | +import java.security.PrivilegedExceptionAction; |
| 7 | + |
| 8 | +/** A serialization proxy for singleton enum values */ |
| 9 | +public final class EnumValueSerializationProxy implements Serializable { |
| 10 | + private static final long serialVersionUID = 1L; |
| 11 | + private final Class<?> enumClass; |
| 12 | + private final int ordinal; |
| 13 | + private static final ClassValue<Object[]> enumValues = new ClassValue<Object[]>() { |
| 14 | + @Override |
| 15 | + protected Object[] computeValue(Class<?> type) { |
| 16 | + try { |
| 17 | + return AccessController.doPrivileged((PrivilegedExceptionAction<Object[]>) () -> |
| 18 | + (Object[])type.getMethod("values").invoke(null)); |
| 19 | + } catch (PrivilegedActionException e) { |
| 20 | + return rethrowRuntime(e.getCause()); |
| 21 | + } |
| 22 | + } |
| 23 | + }; |
| 24 | + |
| 25 | + private static <T> T rethrowRuntime(Throwable e) { |
| 26 | + Throwable cause = e.getCause(); |
| 27 | + if (cause instanceof RuntimeException) throw (RuntimeException) cause; |
| 28 | + else throw new RuntimeException(cause); |
| 29 | + } |
| 30 | + |
| 31 | + public EnumValueSerializationProxy(Class<?> enumClass, int ordinal) { |
| 32 | + this.enumClass = enumClass; |
| 33 | + this.ordinal = ordinal; |
| 34 | + } |
| 35 | + |
| 36 | + @SuppressWarnings("unused") |
| 37 | + private Object readResolve() { |
| 38 | + return enumValues.get(enumClass)[ordinal]; |
| 39 | + } |
| 40 | +} |
0 commit comments