Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate inner class in javapoet in java

Tags:

javapoet

Is there a any way to generate inner classes in javapoet library. I can generate classes with constructors and methods. But i can't figure out how to create inner classes

like image 544
Damith Avatar asked Dec 14 '15 15:12

Damith


People also ask

How do you create an inner class in Java?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.

Can we make inner class as static?

You can only make nested classes either static or non-static. If you make a nested class non-static then it also referred to as Inner class.

How do I add an inner class?

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.

Can you create an inner class inside a method?

Note: We can not have a static method in a nested inner class because an inner class is implicitly associated with an object of its outer class so it cannot define any static method for itself.


1 Answers

Use the TypeSpec.Builder#addType method. See nestedClasses() test in TypeSpecTest.java

like image 55
Sormuras Avatar answered Jan 03 '23 22:01

Sormuras