Import inner enum in Groovy script

橙三吉。 提交于 2019-12-01 06:27:49

Have you tried below?

import static Vehicles.Land.*

println BICYCLE

EDIT: is this what you are looking for?

Groovy does support import nested classes, including enums. However to access them without full qualification, you'll need to import them in a non-static manner (unlike Java), or explicitly declare them static:

// Explicitly declare Water and Air as static to demonstrate
public class Vehicles {
  public enum Land { BICYCLE, CAR, TRAIN }
  public static enum Water { SAILBOAT, MOTORBOAT }
  public static enum Air { JET, HELICOPTER }
}

// Non-static nested enum needs non-static import (unlike Java)
import Vehicles.Land
println Land.BICYCLE

// Explicitly static nested enum can be static imported
import static Vehicles.Water
println Water.SAILBOAT

// Explicitly static nested enum can also be non-static imported as well!
import Vehicles.Air
println Air.JET

Working example: https://groovyconsole.appspot.com/script/5089946750681088

Unlike Java where enums are implicitly static, it appears that enums in Groovy are not implicitly static, hence why static imports don't work. This is because enums in Groovy aren't actually the same as the ones in Java, they made enhancements. Unfortunately it seems they have forgotten to tell the compiler to also make them implicitly static (at least as of 2.4.4).

My suggestion is to explicitly declare them static (if you can) as it would be keeping with the Groovy notion that valid Java is valid Groovy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!