Created
June 30, 2021 10:30
-
-
Save bitristan/285ef021aec159c86887b33621916e49 to your computer and use it in GitHub Desktop.
Create hello world by asm tool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExampleUnitTest { | |
@Test | |
public void helloWorldByAsm() { | |
ClassWriter cw = new ClassWriter(0); | |
cw.visit(V1_8, ACC_PUBLIC, "Hello", null, "java/lang/Object", null); | |
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, | |
"main", "([Ljava/lang/String;)V", null, null); | |
mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); | |
mv.visitLdcInsn("Hello, World"); | |
mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", | |
"println", "(Ljava/lang/String;)V", false); | |
mv.visitInsn(RETURN); | |
mv.visitMaxs(2, 1); | |
mv.visitEnd(); | |
cw.visitEnd(); | |
MyClassLoader classLoader = new MyClassLoader(); | |
Class<?> clazz = classLoader.defineClass("Hello", cw.toByteArray()); | |
try { | |
Method main = clazz.getMethod("main", String[].class); | |
main.invoke(null, new Object[] { new String[] {} }); | |
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { | |
e.printStackTrace(); | |
} | |
} | |
private static class MyClassLoader extends ClassLoader { | |
public Class<?> defineClass(String name, byte[] b) { | |
return super.defineClass(name, b, 0, b.length); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment