3

I have the following case:

I have class with a field and a Annotation:


public class TestClass{

   @Property
   private Object testValue;
}

My goal is to create a Method for each annotated field that would create a "boilerplate code in a lombok like fashion" for the Property for each Value that is annotated that should look like this


  public Object getTestValueProperty{
   return testValue;  
  }

I can access the fields over reflection and anotations, And read the Type etc. But there is no Way to "Create" a Method Structure and adding it to the class on runtime.

I looked into the following: http://notatube.blogspot.com/2010/12/project-lombok-creating-custom.html

But I failed to get access the JavacAnnotationHandler to create the new Method. Since this article is 10 Years Old, I would assume this is not up to date anymore and that there are other ways to "inject" a method into a class.

If you could give me any resources or Ideas how to research this topic I would appriciate it.

Luxusproblem
  • 1,913
  • 11
  • 23
  • Note that Lombok does not create the methods at runtime. It hacks into the compiler and generates the methods during compile-time. – Slaw Apr 19 '20 at 20:46
  • You can research how Project Lombok works by looking at the source code: https://github.com/rzwitserloot/lombok – Slaw Apr 19 '20 at 20:53
  • @Slaw Thats what I also looked into. I thought maybe there is a way to add a " "custom annotation processor" to lombok. Like in the example of the privided link. I don't want to reeinvent the squared wheel. I thought this option existet before, maybe a new Option exits right now... – Luxusproblem Apr 19 '20 at 21:06
  • Related (but also old): https://stackoverflow.com/questions/6680674/can-a-java-class-add-a-method-to-itself-at-runtime – Hulk Apr 19 '20 at 21:07
  • Lombok uses a ShadowClassLoader to load its classes, so you'll have to rename the .scl files to .class files or something like that to be able to access them – user Apr 19 '20 at 21:15
  • 1
    This article talks about what @user mentions in their comment, so maybe it'll be more helpful and up-to-date: https://www.baeldung.com/lombok-custom-annotation – Slaw Apr 19 '20 at 22:38
  • You might also want to look at this answer by one of Lombok's contributors: https://stackoverflow.com/a/57460418/11882002 – user Apr 20 '20 at 13:27

0 Answers0