Search code examples
javagenericsdefault-method

Java Default Method - get type of subclass


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

The method looks like:

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 instantiate AX, I want to use the write method to serialize AX

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

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


Solution

  • I believe what you might be looking for is an interface declaration like this:

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

    Using Self-bounding generics is sometimes useful, when you need to reference the current class as a generic argument. This is e.g. also done by the java Enum class: abstract class Enum<E extends Enum<E>>.