Thursday, September 3, 2009

Java language: referencing current class from static context

Currently, in Java SE 6, to reference the current class from a static context the name of the class is needed. For example:
public class Foo {
public static final valueOf(String s) {
if (s == null) {
return null;
} else if (s.startsWith(Foo.class.getName() + ':')) {
...
} else {
...
}
}
}
However, if this code would be copied to another class, or if the class is renamed, then that code will cause issues, possibly even causing hard-to-find bugs.

Instead it would be nice if the enclosing class could be referenced without using the name. A possible syntax that does not introduce new language keywords could just be:
class
The previous example would then become:
public class Foo {
public static final valueOf(String s) {
if (s == null) {
return null;
} else if (s.startsWith(class.getName() + ':')) {
...
} else {
...
}
}
}
Of course, this construct should also be allowed in non-static code.

One open question is how to deal with inner classes and referencing a certain outer class. I would not mind keeping that out of scope, so the feature only allows referencing the direct enclosing class.

Another issue is subclassing. Would the class statement reference the current class (in case of a non-static context) or the one the method is defined in?

No comments:

Post a Comment