Package samples.reflect.hello1

Source Code of samples.reflect.hello1.HelloWorldBuilder

package samples.reflect.hello1;

import java.io.FileOutputStream;
import java.lang.reflect.Modifier;

import alt.jiapi.reflect.Instruction;
import alt.jiapi.reflect.InstructionFactory;
import alt.jiapi.reflect.InstructionList;
import alt.jiapi.reflect.JiapiClass;
import alt.jiapi.reflect.JiapiMethod;
import alt.jiapi.reflect.Loader;
import alt.jiapi.reflect.Signature;

public class HelloWorldBuilder {
    public static void main(String args[]) throws Exception {
        new HelloWorldBuilder();
    }

    public HelloWorldBuilder() throws Exception {
        // Load the target class:
        Loader loader = new Loader();
        JiapiClass clazz = loader.loadClass("samples.reflect.hello1.Test");
        System.out.println(clazz);

        // Add an empty method for a clazz. The method signature must
        // match the method from HelloWorld interface, the only difference
        // is that we want to implement the method now so it can't be abstract.
        Signature signature = new Signature("void", new String[] {} );
        JiapiMethod method = clazz.addMethod(Modifier.PUBLIC, "helloWorld",
                                             signature);
       
        // Then create the method body. The body will make a call to
        // System.out.println and then just return.
        InstructionList il = method.getInstructionList();
        InstructionFactory iFactory = method.getInstructionFactory();

        JiapiMethod println = clazz.getDeclaredMethod("println", new String[]
                                                      {"java.lang.Object"});

//         il.add(iFactory.getField(loader.loadClass("java.lang.System").getField("out")));
//         JiapiMethod println = loader.loadClass(System.out.getClass().getName()).getMethod("println", new String[] { "java.lang.String" } );

        il.add(iFactory.pushConstant("hello world!"));

        il.add(iFactory.invoke(println));
        il.add(iFactory.returnMethod(method));

        // Finalize the modified class and dump it to the file:

        clazz.dump(new FileOutputStream("Test.class"));
    }
}
TOP

Related Classes of samples.reflect.hello1.HelloWorldBuilder

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.