groovy-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From <eric.mil...@thomsonreuters.com>
Subject RE: `this` in static context
Date Tue, 07 Nov 2017 19:20:41 GMT
Quick correction: `name` or `canonicalName` or `simpleName` cannot be used directly in static
scopes.  You will get "Groovy:Apparent variable 'canonicalName' was found in a static scope
but doesn't refer to a local variable, static field or class."

However, you can use `getName()` or `getCanonicalName()` or `getSimpleName()` etc. directly
or `this.name` or `this.canonicalName` or ... as you stated in your original message.


Two funny thing about all this:
class A { static { this; super } } // "this" here is Class<A> and "super" here is Object
-- Should it be Class<Object>?
class B extends A { static { this; super } } // "this" here is Class<B> and "super"
here is Class<A>

class B extends A { static {
  def closure = {
    this; super // "this" here is Class<B> and "super" here is Class<B> -- Should
it be Class<A>?
  }
}}

From: Milles, Eric (TR Technology & Ops)
Sent: Monday, November 06, 2017 11:59 AM
To: dev@groovy.apache.org
Subject: RE: `this` in static context

You should be able to call `name` or `canonicalName` or `simpleName` directly if there are
no static methods in the class or its supers that would take precedence.

```
class LongClassName {
  private static Logger log = Logger.getLogger(name)
  private static Logger log = Logger.getLogger(this) // another possibility for frameworks
that accept a class instance for logger namespacing
}
```
-- although this particular case has been much simplified by @Log, et al.
Mime
View raw message