Wednesday, 29 April 2020

Javassist: Create new interface at run time

Using ‘makeInterface’ method, you can create new interface.

Step 1: Get an instance of ClassPool.
ClassPool pool = ClassPool.getDefault();

Step 2: Create an interface using makeInterface method.
CtClass ctClass = pool.makeInterface("com.sample.app.interface.Arithmetic");

Step 3: Define methods
CtMethod sum = new CtMethod(CtClass.intType, "sum", new CtClass[] { CtClass.intType, CtClass.intType }, ctClass);
sum.setBody("return $1 + $2;");

CtMethod areaOfCircle = new CtMethod(CtClass.doubleType, "areaOfCircle", new CtClass[] { CtClass.doubleType },ctClass);

Step 4: Add methods to the interface.
ctClass.addMethod(sum);
ctClass.addMethod(areaOfCircle);

Find the below working application.

App.java
package com.sample.app;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class App {

 public static void main(String args[]) throws Exception {
  ClassPool pool = ClassPool.getDefault();

  CtClass ctClass = pool.makeInterface("com.sample.app.interface.Arithmetic");

  CtMethod sum = new CtMethod(CtClass.intType, "sum", new CtClass[] { CtClass.intType, CtClass.intType },
    ctClass);
  sum.setBody("return $1 + $2;");

  CtMethod areaOfCircle = new CtMethod(CtClass.doubleType, "areaOfCircle", new CtClass[] { CtClass.doubleType },
    ctClass);

  ctClass.addMethod(sum);
  ctClass.addMethod(areaOfCircle);

  ctClass.writeFile("/Users/Shared/assistDemos");

 }
}

Run App.java.

You can observe Arithmetic.class file is generated at folder /Users/Shared/assistDemos.
$tree /Users/Shared/assistDemos
/Users/Shared/assistDemos
└── com
    └── sample
        └── app
            └── interface
                └── Arithmetic.class

4 directories, 1 file

Open Arithmetic.class file in decompiler to see the source code.



Previous                                                    Next                                                    Home

No comments:

Post a Comment