Define classes with circular dependency?
Remi Forax
forax at univ-mlv.fr
Sat Mar 15 10:17:58 UTC 2025
Hello,
If you need to define dynamically more than one class, the usual trick is to use an invokedynamic or a constant dynamic so the resolution of the other classes are not done using the ClassLoader but by the code of the bootstrap method of invokedynamic/constant dynamic.
In you case, you can use constant dynamic to initialize the CSSMetaData, by emiting an LDC constant dynamic in the static <clinit> to initialise the static field ('A' in the example).
regards,
Rémi
> From: "John Hendrikx" <john at int4.org>
> To: "classfile-api-dev" <classfile-api-dev at openjdk.org>
> Sent: Saturday, March 15, 2025 10:18:48 AM
> Subject: Define classes with circular dependency?
> Hi list,
> I'm trying to use the ClassFile API to automatically implement control classes
> (as found in JavaFX). These classes define inner class CssMetaData
> implementations that refer back to the outer class, and the outer class refers
> to these implementations via static fields. When I define one of the inner
> types using Lookup::defineClass I get a NoClassDefFoundError for the outer
> type. When I define the outer type first, I get a NoClassDefFoundError for one
> of the inner types. The situation is essentially this:
> public class Sample {
> private final Property b = new Property( A );
> private static final CssMetaData A = new CssMetaData() {
> @Override
> public Property getProperty(Object obj) {
> return ((Sample)obj). b ;
> }
> };
> }
> abstract class CssMetaData {
> abstract Property getProperty(Object obj);
> }
> class Property {
> public Property(CssMetaData a ) {
> }
> }
> I'm trying to generate the Sample class. The classes CssMetaData and Propery are
> pre-existing. As you can see, Sample refers to A in a property it creates,
> while A refers to that property by direct field access after a cast.
> Note that the above is perfectly legal as a Java class, and I think the bytecode
> I generate is correct. It seems I would need to be able to define both classes
> at the same time, but Lookup doesn't seem to have anything for this purpose.
> I'd appreciate any insights!
> --John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/classfile-api-dev/attachments/20250315/e385d5a7/attachment-0001.htm>
More information about the classfile-api-dev
mailing list