Created
June 8, 2011 16:05
-
-
Save hns/1014719 to your computer and use it in GitHub Desktop.
Example from http://code.google.com/p/jsr292-cookbook/source/browse/trunk/lazy-init/src/jsr292/cookbook/lazyinit/ ported to Rhino Class writer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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