fork download
  1. import java.io.IOException;
  2. import java.lang.invoke.MethodHandles;
  3. import java.nio.ByteBuffer;
  4. import java.nio.charset.StandardCharsets;
  5.  
  6. public class Main {
  7. interface Foo {
  8. public void bar();
  9. }
  10. enum MyEnum {
  11. A {
  12. public void bar() {
  13. System.out.println("Hello!");
  14. }
  15. },
  16. B,
  17. C;
  18. }
  19. public static void main(String[] arg) {
  20. try {
  21. patch();
  22. System.err.println("patching failed: "+ex);
  23. return;
  24. }
  25. test();
  26. }
  27. static void test() {
  28. for(MyEnum e: MyEnum.values()) {
  29. System.out.println(e.name());
  30. if (e instanceof Foo) {
  31. System.out.println("\timplements Foo");
  32. ((Foo)e).bar();
  33. }
  34. }
  35. }
  36. private static void patch() throws IOException, IllegalAccessException {
  37. ByteBuffer bb = ByteBuffer.wrap(Main.class
  38. .getResourceAsStream("Main$MyEnum$1.class").readAllBytes());
  39. int poolSize = bb.position(8).getChar();
  40. for(int ix = 1; ix < poolSize; ix++) {
  41. byte tag = bb.get();
  42. switch(tag) {
  43. default: bb.position(bb.position() + 4); break;
  44. case 1: bb.position(bb.getChar() + bb.position()); break;
  45. case 7: case 8: case 16: case 19: case 20:
  46. bb.position(bb.position() + 2); break;
  47. case 5: case 6: bb.position(bb.position() + 8); ix++; break;
  48. case 15: bb.position(bb.position() + 3);
  49. }
  50. }
  51. ByteBuffer newBB = ByteBuffer.allocate(bb.capacity() + 16);
  52. newBB.put(bb.duplicate().flip());
  53. int ifType = poolSize;
  54. newBB.putShort(8, (short)(poolSize + 2));
  55. newBB.put((byte)7).putShort((short)(ifType + 1));
  56. byte[] ifName = "Main$Foo".getBytes(StandardCharsets.UTF_8);
  57. newBB.put((byte)1).putShort((short)ifName.length).put(ifName);
  58. bb.limit(bb.position() + 6);
  59. newBB.put(bb);
  60. bb.limit(bb.capacity());
  61. newBB.putShort((short)(bb.getShort() + 1)).putShort((short)ifType);
  62. newBB.put(bb);
  63. MethodHandles.lookup().defineClass(newBB.array());
  64. }
  65. }
Success #stdin #stdout 0.08s 33760KB
stdin
Standard input is empty
stdout
A
	implements Foo
Hello!
B
C