Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. package com.krb;
  2.  
  3.  
  4. import java.io.PrintStream;
  5. import org.objectweb.asm.ClassWriter;
  6. import org.objectweb.asm.Opcodes;
  7. import org.objectweb.asm.Type;
  8. import org.objectweb.asm.commons.GeneratorAdapter;
  9. import org.objectweb.asm.commons.Method;
  10.  
  11. public class Helloworld extends ClassLoader implements Opcodes {
  12.  
  13. public static void main(final String args[]) throws Exception {
  14.  
  15. // Generates the bytecode corresponding to the following Java class:
  16. //
  17. // public class Example {
  18. // public static void main (String[] args) {
  19. // System.out.println("Hello world!");
  20. // }
  21. // }
  22.  
  23. // creates a ClassWriter for the Example public class,
  24. // which inherits from Object
  25. ClassWriter cw = new ClassWriter(0);
  26.  
  27. cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
  28. cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null);
  29.  
  30. // creates a GeneratorAdapter for the (implicit) constructor
  31. Method m = Method.getMethod("void <init> ()");
  32. GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC,
  33. m,
  34. null,
  35. null,
  36. cw);
  37. mg.loadThis();
  38. mg.invokeConstructor(Type.getType(Object.class), m);
  39. mg.returnValue();
  40. mg.endMethod();
  41.  
  42. // creates a GeneratorAdapter for the 'main' method
  43. m = Method.getMethod("void main (String[])");
  44. mg = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw);
  45. mg.getStatic(Type.getType(System.class),
  46. "out",
  47. Type.getType(PrintStream.class));
  48. mg.push("Hello world!");
  49. mg.invokeVirtual(Type.getType(PrintStream.class),
  50. Method.getMethod("void println (String)"));
  51. mg.returnValue();
  52. mg.endMethod();
  53.  
  54. cw.visitEnd();
  55.  
  56. byte[] code = cw.toByteArray();
  57. Helloworld loader = new Helloworld();
  58. Class exampleClass = loader.defineClass("Example", code, 0, code.length);
  59.  
  60. // uses the dynamically generated class to print 'Helloworld'
  61. exampleClass.getMethods()[0].invoke(null, new Object[] { null });
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement