1 Reply Latest reply on Jul 19, 2012 3:45 PM by pulce

    Compile problem with interface initialization

    pulce

      Hi there! I implemented code to my project that makes use of javassist. However, I constantly fail to implement an interface to a new class I create. Here is the code I use (adapted from http://www.javaranch.com/journal/200711/Journal200711.jsp#a4):

       

       

      Main file:

      package test;

      import javassist.*;

      public class Example2 {

           public static void main (String[] args) throws Exception {

              ClassPool pool = ClassPool.getDefault();

              CtClass evalClass = pool.makeClass("Eval"+System.currentTimeMillis());

             evalClass.setInterfaces(new CtClass[] { pool.makeClass("Evaluator") });

             evalClass.addMethod(CtNewMethod.make("public double eval (double x) { return (x*x-x) ; }", evalClass));

             Class clazz = evalClass.toClass();

             Evaluator obj  = (Evaluator) clazz.newInstance();

             double result = obj.eval(4);

             System.out.println(result);

          }

      }

       

      Interface "Evaluator":

      package test;

      public interface Evaluator {

           public double eval (double x);

      }

       

      The code works like a charm in the default package of an Eclipse project (without package test; of course). However, when I use it in a package, I get an Error:

      javassist.CannotCompileException: by java.lang.NoClassDefFoundError: Evaluator

       

      From trial and interpreting different error messages I guess that the class loader that should load "Evaluator" refers to the /bin path, while the Evaluator.class file is to be found in the /bin/test folder. Is there a way to solve that? Many thanks in advance!

        • 1. Re: Compile problem with interface initialization
          pulce

          Solved my issue, was quite obvious. When using the above code in a package, the .setInterfaces command must refer to the fully qualified name. Assuming the two files are in package "test", one must cast

           

          evalClass.setInterfaces(new CtClass[] { pool.makeClass("test.Evaluator") });