Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaPoet - Field of type inner class

Tags:

java

javapoet

I am trying to add an inner class (e.g. interface Listener{}) to a TypeSpec. Also I want to add a field of type Listener to my TypeSpec. How could i achieve something like that?

TypeSpec outerClass = ...;
TypeSpec innerClass = ...;
outerClass.addType(innerClass);
outerClass.addField(...); // How can i add a field of type innerClass?
like image 473
Saeed Entezari Avatar asked Dec 22 '16 07:12

Saeed Entezari


1 Answers

You’ll need to compute the fully-qualified name of the type. That’ll look like this:

ClassName outerName = ClassName.get("com.example.project", "Outer");
ClassName innerName = outerName.nestedClass("Inner");

Then you can call outerClass.addField() passing innerName.

like image 144
Jesse Wilson Avatar answered Oct 17 '22 22:10

Jesse Wilson