01: /**
02: * EasyBeans
03: * Copyright (C) 2007 Bull S.A.S.
04: * Contact: easybeans@ow2.org
05: *
06: * This library is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU Lesser General Public
08: * License as published by the Free Software Foundation; either
09: * version 2.1 of the License, or any later version.
10: *
11: * This library is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * Lesser General Public License for more details.
15: *
16: * You should have received a copy of the GNU Lesser General Public
17: * License along with this library; if not, write to the Free Software
18: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19: * USA
20: *
21: * --------------------------------------------------------------------------
22: * $Id: GenerateClass.java 2057 2007-11-21 15:35:32Z benoitf $
23: * --------------------------------------------------------------------------
24: */package org.ow2.easybeans.component.smartclient.test;
25:
26: import org.ow2.easybeans.asm.ClassWriter;
27: import org.ow2.easybeans.asm.MethodVisitor;
28: import org.ow2.easybeans.asm.Opcodes;
29:
30: /**
31: * Allow to generate dynamically a class.
32: * @author Florent BENOIT
33: */
34: public final class GenerateClass implements Opcodes {
35:
36: /**
37: * Utility class, no public constructor.
38: */
39: private GenerateClass() {
40:
41: }
42:
43: /**
44: * Gets the bytecode for the given generated classname and the content of
45: * the hello() method.
46: * @param className the name of the class to generate
47: * @param helloWorldString the content that hello() method will return
48: * @return the bytecode
49: * @throws Exception if bytecode can't be built
50: */
51: public static byte[] getByteForClass(final String className,
52: final String helloWorldString) throws Exception {
53:
54: ClassWriter cw = new ClassWriter(0);
55: MethodVisitor mv;
56: cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, null,
57: "java/lang/Object", null);
58:
59: // Constructor
60: mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
61: mv.visitCode();
62: mv.visitVarInsn(ALOAD, 0);
63: mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>",
64: "()V");
65: mv.visitInsn(RETURN);
66: mv.visitMaxs(1, 1);
67: mv.visitEnd();
68:
69: // hello method
70: mv = cw.visitMethod(ACC_PUBLIC, "hello",
71: "()Ljava/lang/String;", null, null);
72: mv.visitCode();
73: mv.visitLdcInsn(helloWorldString);
74: mv.visitInsn(ARETURN);
75: mv.visitMaxs(1, 1);
76: mv.visitEnd();
77:
78: cw.visitEnd();
79:
80: return cw.toByteArray();
81: }
82:
83: }
|