Anonymity and observability of unnamed classes (JEP 445)

Attila Kelemen attila.kelemen85 at gmail.com
Sat May 6 13:15:29 UTC 2023


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


More information about the jdk-dev mailing list