The default Java method is to get the type of the subclass.

I have an interface in which I want to provide a default method for serializing inherited classes. I use the class JsonSerializer<T>for serialization.

The method looks like this:

public interface A
{
    public default String write()
    {
        new JsonSerializer</*Inherited class type*/>();
        // I've tried new JsonSerializer<this.getClass()>();  - Doesn't work

    }
}

public class AX implements A
{
}

So when I create an AX instance, I want to use the write method to serialize AX

AX inst = new AX();
String instSerialized = inst.write();

I need to pass type AX to the write method in A. Is this possible?

+4
source share
3 answers

I believe what you might be looking for is an interface declaration similar to this:

public interface A<T extends A<T>>
{
    public default String write()
    {
        new JsonSerializer<T>();
    }
}

public class AX implements A<AX>
{
}

, . , , java Enum: abstract class Enum<E extends Enum<E>>.

+2

generics - . -.

( getClass()) - .

: , - .

-

new JsonSerializer<? extends A>() ...

: ? , .

+1

Use generics in the interface

public interface A<T> {

    public default String write() {
        new JsonSerializer<T>();
        // I've tried new JsonSerializer<this.getClass()>();  - Doesn't work
    }
}

public class AX implements A<AX> {
}
+1
source

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


All Articles