0

I'm searching for a solution where I can define a field in a class and use the reference in this particular class. The codemodel should create a method for instantiating the field and should replace the field usages with the created method.

I hope somebody can help me.

unprocessed Class

public class MyClass {
    @LazyInit
    CustomClass member;

    public void someMethod() {
        System.out.println(member);
    }
}

Class after codeModel usage

public class MyClass_ {
    @LazyInit
    CustomClass member;

    public void someMethod() {
        System.out.println(getInstanceOfMember());
    }

    public member getInstanceOfMember() {
        if (member == null)
            member == new CustomClass();

        return member;
    }
}
alosdev
  • 384
  • 2
  • 14
  • What have you tried? [Please read this.](http://mattgemmell.com/2008/12/08/what-have-you-tried/) Try posting some code. – durron597 Nov 16 '12 at 15:53
  • Your question is not very clear, could you try rewording it. Maybe giving a small example of what the input would be, and what the desired out would be could clear it up. – Jacob Schoen Nov 16 '12 at 15:56
  • thanks for hint updated the question with code example. :) – alosdev Nov 16 '12 at 16:03

1 Answers1

0

If you change things a bit, then this problem becomes much more manageable. By changing the variable to an abstract getter method, then you can perform the lazy init in the generated class while leaving the base class alone. Here's what I mean:

Input Class:

public abstract class MyClass {
    @LazyInit
    public abstract CustomClass getMember();

    public void someMethod() {
        System.out.println(getMember());
    }
}

Generated Class:

public class MyClass_ extends MyClass {

    private CustomClass member;

    public synchronized CustomClass getMember() {
        if (member == null){
            member == new CustomClass();
        }
        return member;
    }
}

Then to use this generated class, you can either instantiate it directly or use a utility:

new MyClass_().someMethod(); // prints CustomClass.toString() (non-null)

or

Lazy.get(MyClass.class).someMethod() // same

Implementing this with an annotation processor and a code generator (like JCodeModel) is pretty straight forward. Let me know if you need details around that.

John Ericksen
  • 10,995
  • 4
  • 45
  • 75