Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

55
LINES

< > BotCompany Repo | #1034311 // Test making class from scratch with BCEL using MethodMaker [OK]

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Uses 1311K of libraries. Click here for Pure Java version (5515L/26K).

1  
!7
2  
3  
set flag AllPublic.
4  
5  
p {
6  
  ClassGen cg = new("User123", "java.lang.Object", null,
7  
    Const.ACC_PUBLIC, new S[] { className(IF0) });
8  
  cg.addEmptyConstructor(Const.ACC_PUBLIC);
9  
  
10  
  // make code for get() method
11  
  
12  
  var m = new MethodMaker(cg, "get", O);
13  
  
14  
  // declare and create StringBuffer
15  
  
16  
  int buffer = m.newLocalVar();
17  
  m.newObject(StringBuffer.class).astore(buffer);
18  
  
19  
  // Append two strings
20  
  
21  
  for (string : ll("Hello ", "world")) {
22  
    m.aload(buffer).stringConstant(string);
23  
    m.il.append(m.factory.createAppend(org.apache.bcel.generic.Type.OBJECT));
24  
  }
25  
  
26  
  // call StringBuffer.toString() and return
27  
  
28  
  m.aload(buffer);
29  
  m.invokeVirtual(StringBuffer.class, "toString", S);
30  
  m.areturn().done();
31  
  
32  
  // bake class
33  
  JavaClass baked = cg.getJavaClass();
34  
  
35  
  // print class overview
36  
  print(baked);
37  
  
38  
  // print the methods
39  
  for (method : baked.getMethods()) {
40  
    print("\n" + method);
41  
    print(method.getCode());
42  
  }
43  
  
44  
  byte[] bytes = baked.getBytes();
45  
  var cl = new InMemoryClassLoader(myClassLoader());
46  
  
47  
  time "Defining class" {
48  
    Class<? extends IF0> c = cast cl.defineAClass("User123", bytes);
49  
  }
50  
  print(c);
51  
  
52  
  IF0 f = newInstance(c);
53  
  print(f);
54  
  assertEqualsVerbose("Hello world", f!);
55  
}

Author comment

Began life as a copy of #1034300

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): bhatertpkbcr, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1034311
Snippet name: Test making class from scratch with BCEL using MethodMaker [OK]
Eternal ID of this version: #1034311/6
Text MD5: 43fc1b77ed7e2cfd6b8c3028cb1c75b8
Transpilation MD5: d1836f076f538d57b24613d038f4f154
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-02-01 20:38:57
Source code size: 1297 bytes / 55 lines
Pitched / IR pitched: No / No
Views / Downloads: 228 / 832
Version history: 5 change(s)
Referenced in: [show references]