Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fully qualified class name of an enum defined locally within a method?

As of Java 16, we can now define an enum locally, within a method. This feature came as part of the work for the new records feature. (Interfaces too can be local, by the way.)

What is the fully-qualified name of such a locally-defined enum class?

The following code works if I were define the enum in a separate .java file. How should I change this fully-qualified class name for a local enum?

package work.basil.example.enums;

public class EnumMagic
{
    public static void main ( String[] args )
    {
        EnumMagic app = new EnumMagic ( );
        app.demo ( );
    }

    private void demo ( )
    {
        enum Shape { CIRCLE, SQUARE }
        try
        {
            Class < ? > clazz = Class.forName ( "work.basil.example.enums.Shape" );
            System.out.println ( "clazz = " + clazz );
        }
        catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ); }
    }
}

As currently written, I understandably get an java.lang.ClassNotFoundException: work.basil.example.enums.Shape.

Neither of these work:

  • "work.basil.example.enums.EnumMagic.Shape"
  • "work.basil.example.enums.EnumMagic.$Shape"
like image 353
Basil Bourque Avatar asked Sep 06 '25 03:09

Basil Bourque


1 Answers

Local classes, enums and interfaces don't have a qualified name. Just a simple name. In your case: Shape

From: https://docs.oracle.com/javase/specs/jls/se15/preview/specs/local-statics-jls.html#jls-14.3

like image 164
Mar-Z Avatar answered Sep 07 '25 20:09

Mar-Z