I've been looking into the ASM library. First I wrote a program to build a hello world class and then I thought I'd try something a little more involved, build a class that creates a PythonInterpreter(part of the the Jython library) and executes a python file. The result is the following, unfortunately I get the exception I named this question after when I try to execute the resulting class.
public class Main {
public static void main(String[] args) {
String mainFile = "main.py";
ClassWriter mainClass = new ClassWriter(ClassWriter.COMPUTE_MAXS);
mainClass.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "Main", null, "java/lang/Object", null);
MethodVisitor mainMethod = mainClass.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
mainMethod.visitTypeInsn(Opcodes.NEW, "org/python/util/PythonInterpreter");
mainMethod.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/python/util/PythonInterpreter", "<init>", "()V");
mainMethod.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
mainMethod.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/python/util/PythonInterpreter", "setOut", "(Ljava/io/PrintStream;)V");
mainMethod.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "err", "Ljava/io/PrintStream;");
mainMethod.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/python/util/PythonInterpreter", "setErr", "(Ljava/io/PrintStream;)V");
mainMethod.visitLdcInsn(mainFile);
mainMethod.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/python/util/PythonInterpreter", "execFile", "(Ljava/lang/String;)V");
mainMethod.visitInsn(Opcodes.RETURN);
mainMethod.visitEnd();
mainClass.visitEnd();
try{
byte[] b = mainClass.toByteArray();
FileOutputStream writer = new FileOutputStream("Main.class");
writer.write开发者_JS百科(b);
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
When you come to the setOut
and setErr
methods, you have only an argument, and no object to invoke the method on. (The call to <init>
"consumed" the object it initialized!)
Same applies for the call to execFile
. You have an argument (mainFile
) but no object to invoke execFile
on.
Try to add three DUP
instructinos right after NEW
. (To save enough references for the three method calls you want to do on that object.)
精彩评论