package net.bytebuddy.implementation.bytecode.constant;
import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bytecode.Duplication;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.TypeCreation;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import org.objectweb.asm.MethodVisitor;
import java.io.*;
@HashCodeAndEqualsPlugin.Enhance
public class SerializedConstant implements StackManipulation {
private static final String CHARSET = "ISO-8859-1";
private final String serialization;
protected SerializedConstant(String serialization) {
this.serialization = serialization;
}
public static StackManipulation of(Serializable value) {
if (value == null) {
return NullConstant.INSTANCE;
}
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
try {
objectOutputStream.writeObject(value);
} finally {
objectOutputStream.close();
}
return new SerializedConstant(byteArrayOutputStream.toString(CHARSET));
} catch (IOException exception) {
throw new IllegalStateException("Cannot serialize " + value, exception);
}
}
public boolean isValid() {
return true;
}
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
try {
return new StackManipulation.Compound(
TypeCreation.of(TypeDescription.ForLoadedType.of(ObjectInputStream.class)),
Duplication.SINGLE,
TypeCreation.of(TypeDescription.ForLoadedType.of(ByteArrayInputStream.class)),
Duplication.SINGLE,
new TextConstant(serialization),
new TextConstant(CHARSET),
MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(String.class.getMethod("getBytes", String.class))),
MethodInvocation.invoke(new MethodDescription.ForLoadedConstructor(ByteArrayInputStream.class.getConstructor(byte[].class))),
MethodInvocation.invoke(new MethodDescription.ForLoadedConstructor(ObjectInputStream.class.getConstructor(InputStream.class))),
MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(ObjectInputStream.class.getMethod("readObject")))
).apply(methodVisitor, implementationContext);
} catch (NoSuchMethodException exception) {
throw new IllegalStateException("Could not locate Java API method", exception);
}
}
}