How to access @Singleton classes from Java classes?

I was just playing around with the Groovy support of IntelliJ. How can I access classes that are marked with @Singleton from a Java class?

Suppose, I have something like

@Singleton
class PointHolder {
  def registeredPoints = []

  def addPoint(Point point) {
    registeredPoints << point
  }
}



As I understand the description, there should be a method

public static PointHolder getInstance()

available but IDEA highlights that as error and also gives a compilation error.

Thanks,
Dirk
5 comments
Comment actions Permalink

> How can I access classes that are marked with @Singleton from a Java class?

You cannot. This is not an IDEA issue, but a known limitation of the Groovy compiler.

Cheers,
Peter

0
Comment actions Permalink

More accurately, this does work when Groovy and Java code are compiled separately (live in separate modules), but not when they are compiled together (live in the same module).

0
Comment actions Permalink

I have separated Java and Groovy code into two modules. I can now compile the code but code completion doesn't work anymore. But that's something that I can live with for the time being.

How do you set up your projects? Do you mix Java and Groovy classes or do you keep them separate?

Thanks for the info,
Dirk

0
Comment actions Permalink

Groovy's goal is to allow arbitrary mixing of Java and Groovy code. Although this already works in principle, there are still quite a few problems to solve for it to work reliably in different build environments (command line, build tools, IDEs) and for non-trivial projects. Depending on your needs and your willingness to live on the cutting edge, I would choose one of the following strategies:

  1. Put Java and Groovy code into different modules. Safest but least flexible.
  2. Put Java and Groovy into the same module, but only call from Groovy into Java, not vice versa. In this case you can turn off joint compilation. In IDEA you do this with "Settings->Compiler->Groovy Compiler->Exclude from stub generation".
  3. Mix Java and Groovy arbitrarily. You gain a lot of flexibility, but might run into some issues here and there (like the inability to use language features based on AST transforms (@Singleton, @Delegate, etc.) from Java). These issues will eventually be fixed, but it could take some time. Please report any problems you encounter, preferably on the Groovy mailing list.


Cheers,
Peter

0
Comment actions Permalink

9 years later this still seems to be an issue. Has there been any progress? I am using Groovy Eclipse Compiler 2.4.15 from Maven.

0

Please sign in to leave a comment.