I have had a bit of a problem a few times where I want to do something like this:
interface MyInterface
{
public Validator<this.class> getValidator();
}
class MyInstance implements MyInterface
{
public Validator<this.class> getValidator()
{
//do stuff
}
}
So to be able to pass a reference to the concrete class as a generic parameter, it is often needed when you have classes that act on the current class. A simple solution is to use the ? type, but it's not ideal when you then need to access values in the class itself (eg. if you needed to do something like getValidator().validateForm().getField()) or even if you want to subclass a class with chained methods (like the StringBuilder.append())
The way I have usually had to do it like this:
interface MyInterface<T>
{
public Validator<T> getValidator();
}
class MyInstance implements MyInterface<MyInstance>
{
public Validator<MyInstance> getValidator()
{
//do stuff
}
}
but that is quite ugly, and it is easy to accidentally put the wrong class as the parameter.
Are there any other solutions to this one?
Edit: The answers provided by 'Is there a way to refer to the current type with a type variable?' currently do not solve this problem (apart from the Scala answer)