1

I need to generate a class which must have a method that returns an object of the same class.

I want to generate something like this

public class A{
   public A method1(){
       ...
   }
 }

The problem is that I have to pass the Class object of the class being returned by the method. If i do that, because my class is not built yet I will get a ClassNotFoundException. Is there a way of achieving this?

Thanks.

theAsker
  • 527
  • 3
  • 14
  • Are you looking to return `this` or a `new A()`? – John Ericksen Nov 13 '15 at 17:17
  • It didn't matter because the problem was that i didn't know how to obtain a JClass reference for class A, since I thought you must provide the Class object representing your class in order to build its corresponding JClass object. Luckily, I managed to find the solution. Thanks for trying to help though ! – theAsker Nov 14 '15 at 18:05

2 Answers2

2

After a little digging I managed to find the solution. If you do not have access to a class and thus you cannot provide its corresponding Class object, use the method directClass(String className) from Codemodel object which takes as input a String representing the class name and returns the corresponding JClass object.

theAsker
  • 527
  • 3
  • 14
0

You can use the CodeModel JDefinedClass to reference the containing class during class generation:

    JDefinedClass aClass = codeModel._class(JMod.PUBLIC, "A", ClassType.CLASS);
    JMethod method= aClass.method(JMod.PUBLIC, aClass, "method1");
    method.body()._return(JExpr._new(aClass));

Outputs:

public class A {
    public A method1() {
        return new A();
    }
}
John Ericksen
  • 10,995
  • 4
  • 45
  • 75