Anonymity and observability of unnamed classes (JEP 445)

Holo The Sage Wolf holo3146 at gmail.com
Sat May 6 16:14:29 UTC 2023


The unnamed class doesn't have fully qualified name (or a canonical one) at
all.

The JLS does not touch the implementation of the concept, so different
vendors can implement it differently, but in the draft JLS it states that
in simple implementations the compiler may put the unnamed class in a class
named after the file name (±`.java`)

I'm not sure about reflection but I would assume that it is not part of the
JLS as well.

As for the last point, yes the unnamed class is a member of the unnamed
package in the unnamed module

On Sat, May 6, 2023, 16:15 Attila Kelemen <attila.kelemen85 at gmail.com>
wrote:

> 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`?
>
>
> 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);
> }
> ```
>
> Are the `setAccessible` calls required? Even if the class of the
> `test` method is also in the unnamed module?
>
>
> 3. Am I assuming correctly, that the unnamed classes are required to
> be in the unnamed package?
>
>
> Thanks,
> Attila
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/jdk-dev/attachments/20230506/53da1007/attachment.htm>


More information about the jdk-dev mailing list