Anonymity and observability of unnamed classes (JEP 445)

Remi Forax forax at univ-mlv.fr
Sat May 6 16:34:49 UTC 2023


----- Original Message -----
> From: "attila kelemen85" <attila.kelemen85 at gmail.com>
> To: "jdk-dev" <jdk-dev at openjdk.org>
> Sent: Saturday, May 6, 2023 3:15:29 PM
> Subject: Anonymity and observability of unnamed classes (JEP 445)

> Hi,


Hi,

> 
> I have some questions about the anonymity and observability of the
> unnamed classes defined in JEP 445:
> 
> 1. Will the JLS define a name for the unnamed classes? That is, I
> assume it probably should, because I will have to specify it to the
> `java` command. In other words, would this code have a well defined
> behaviour?
> 
> ```
> void main() {
>  println(getClass().getName());
> }
> ```
> 
> If in the above code, we don't have a well defined name, then -
> assuming this unnamed class is in *Main.java* - can I create a normal
> class (in another directory or a non-public top level in another file)
> called `Main`?

There is a name, but it is not well defined, like an anonymous class has a name.

Since Java 11, you do not need a class name to run a class, you can specify the file name, e.g. java foo.java, it will compile the class in memory and then execute it's method main.

The generated class has no package (it uses the unnamed package), is final and is marked as synthetic so it is not visible as a name for javac (but it is visible for the VM).

> 
> 
> 2. This depends on the previous, but can I access this class via
> reflection? If yes, then what if I want to create a new instance of
> it, and call its method (say, for testing purposes)? That is, see the
> following hypothetical code:
> 
> ```
> void test() throws Exception {
>  var unnamedClass = Class.forName("Main"); // Assume this works.
>  var constr = unnamedClass.getConstructor();
>  constr.setAccessible(true); // Do I need this?
>  var obj = constr.newInstance();
>  var m = unnamedClass.getDeclaredMethod("main");
>  m.setAccessible(true); // Do I need this?
>  m.invoke(obj);
> }
> ```

It is accessible by reflection, otherwise the launcher will not be able to run it (the launcher of the VM is itself written in Java).

> 
> Are the `setAccessible` calls required? Even if the class of the
> `test` method is also in the unnamed module?

You need setAccessible() if the test class is not in the unammed package (a class can be in a named package and in the unnamed module).

> 
> 
> 3. Am I assuming correctly, that the unnamed classes are required to
> be in the unnamed package?

yes

> 
> 
> Thanks,
> Attila

regards,
Rémi



More information about the jdk-dev mailing list