Can you refer to the class 'this' as a generic parameter?

I had a little problem a few times when 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, in order to be able to pass a reference to a specific class as a general parameter, this is often necessary if you have classes acting on the current class. Easy solution - use? type, but it is not ideal when you need to access values ​​in the class itself (for example, if you need to do something like getValidator().validateForm().getField()) or even if you want to subclass the class using chain methods (for example, StringBuilder.append())

As usual, I 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 it's pretty ugly, and it's easy to accidentally put the wrong class as a parameter.

Are there any other solutions for this?


: , " ?" ( Scala)

+4
2

, , "", , .

, , :

interface MyInterface {
    Validator<? extends MyInterface> getValidator();
}

MyInterface , . ( , MyInstance Validator<MyInstance>.)

, .

+2

, , .

, List<Dog> List<Animal>.

, , , :

class MyInstance implements MyInterface
{
     public Validator<MyInstance> getValidator()

getValidator() "" Validator<MyInterface> ( this.class MyInterface )

Validator<MyInstance> Validator<MyInterface>.

, , , Validator<MyOtherInstance>, Validator<MyInterface>. Validator<MyInstance>, , , MyInstance MyOtherInstance.

0

Source: https://habr.com/ru/post/1618363/


All Articles