Created
February 25, 2012 05:48
-
-
Save zakki/1906715 to your computer and use it in GitHub Desktop.
JVM method overload
This file contains 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
package test; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.lang.reflect.Method; | |
import org.objectweb.asm.ClassWriter; | |
import org.objectweb.asm.MethodVisitor; | |
import org.objectweb.asm.Opcodes; | |
public class Make implements Opcodes { | |
public static void main(String[] args) { | |
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); | |
cw.visit(V1_1, ACC_PUBLIC, "test/Ov", null, "java/lang/Object", null); | |
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, | |
"<init>", | |
"()V", | |
null, | |
null); | |
mv.visitVarInsn(ALOAD, 0); | |
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); | |
mv.visitInsn(RETURN); | |
mv.visitMaxs(1, 1); | |
mv.visitEnd(); | |
mv = cw.visitMethod(ACC_PUBLIC, "a", "()I", null, null); | |
mv.visitLdcInsn(Integer.valueOf(10)); | |
mv.visitInsn(IRETURN); | |
mv.visitMaxs(0, 0); | |
mv.visitEnd(); | |
mv = cw.visitMethod(ACC_PUBLIC, "a", "()Ljava/lang/String;", null, null); | |
mv.visitLdcInsn("abc"); | |
mv.visitInsn(ARETURN); | |
mv.visitMaxs(0, 0); | |
mv.visitEnd(); | |
try { | |
FileOutputStream out = new FileOutputStream("lib/test/Ov.class"); | |
out.write(cw.toByteArray()); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
class Run { | |
public static void main(String[] args) throws Exception { | |
Ov ov = new Ov(); | |
Method[] methods = ov.getClass().getDeclaredMethods(); | |
for (Method m : methods) { | |
System.out.println(m); | |
if (m.getName().equals("a")) { | |
System.out.println(m.invoke(ov)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment