Skip to content

Instantly share code, notes, and snippets.

@hns
Created June 8, 2011 16:05
Show Gist options
  • Save hns/1014719 to your computer and use it in GitHub Desktop.
Save hns/1014719 to your computer and use it in GitHub Desktop.
package jsr292.cookbook.lazyinit;
import sun.misc.BASE64Encoder;
import java.io.IOException;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.mozilla.classfile.ClassFileWriter;
import static org.mozilla.classfile.ByteCode.*;
/*
public class Main {
public static void main(String[] args) {
System.out.println(java.util.Arrays.toString( {'h', 'e', 'l', 'l', 'o'} ));
}
}
*/
public class Gen {
private static final ClassFileWriter.MethodHandle BSM =
new ClassFileWriter.MethodHandle(MH_INVOKESTATIC,
RT.class.getName().replace('.', '/'),
"bootstrap",
MethodType.methodType(
CallSite.class, Lookup.class, String.class, MethodType.class, String.class
).toMethodDescriptorString());
@SuppressWarnings("restriction")
public static void main(String[] args) throws IOException {
ClassFileWriter cw = new ClassFileWriter("Main2", "java/lang/Object", null);
cw.startMethod("main", "([Ljava/lang/String;)V",
(short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_STATIC));
cw.add(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
byteBuffer.asCharBuffer().put("hello".toCharArray());
BASE64Encoder base64Encoder = new BASE64Encoder();
String base64 = base64Encoder.encode(byteBuffer);
cw.addInvokeDynamic("const", "()[C", BSM, base64);
cw.addInvoke(INVOKESTATIC, "java/util/Arrays", "toString", "([C)Ljava/lang/String;");
cw.addInvoke(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
cw.add(RETURN);
cw.stopMethod((short)1);
Files.write(Paths.get("Main2.class"), cw.toByteArray());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment