// File RTCG2B.java --- calling a static method with int argument and result // sestoft@itu.dk * 2002-09-17 // Using BCEL from http://jakarta.apache.org/bcel/ import org.apache.bcel.*; // Constants import org.apache.bcel.classfile.*; // JavaClass import org.apache.bcel.generic.*; // ClassGen, MethodGen, instructions import java.io.*; public class RTCG2B { public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, java.lang.reflect.InvocationTargetException { ClassGen cg = new ClassGen("MyClass", "java.lang.Object", "", Constants.ACC_PUBLIC | Constants.ACC_SUPER, null); ConstantPoolGen cp = cg.getConstantPool(); { // Build: public static int MyMethod(int x) { ... } InstructionList il = new InstructionList(); MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_STATIC, Type.INT, new Type[] { Type.INT }, new String[] { "x" }, "MyMethod", "MyClass", il, cp); il.append(new ILOAD(0)); il.append(new ICONST(2)); il.append(InstructionConstants.IADD); il.append(InstructionConstants.IRETURN); // Compute stack depth and add method to the class mg.setMaxStack(); cg.addMethod(mg.getMethod()); } // Get the generated class JavaClass clazz = cg.getJavaClass(); // Output class in human-readable format: System.out.println(clazz); // Output method body in human-readable format: System.out.println(clazz.getMethods()[0].getCode()); // Output class file to class file on disk: clazz.dump("MyClass.class"); // Output class file to array: byte[] classFile = clazz.getBytes(); // Load the class file from byte array into the JVM Class ty = new ArrayClassLoader().loadClass("MyClass", classFile); // Get the MyMethod(int): java.lang.reflect.Method m = ty.getMethod("MyMethod", new Class[] { int.class }); // Call the method: System.out.println(m.invoke(null, new Object[] { new Integer(5) })); } } // This is needed because defineClass is protected in java.lang.ClassLoader: class ArrayClassLoader extends ClassLoader { public Class loadClass(String name, byte[] classFile) { return defineClass(name, classFile, 0, classFile.length); } }