Question

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?

Was it helpful?

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>>.

OTHER TIPS

The type parameters in the generics mechanism are a compile-time information, only. This type information is erased in the bytecode.

The exact class type of an object (which you can retrieve with getClass()) is a runtime information.

The conclusion: As you can only put static type names inside the generics brackets, there is no way to make any runtime calls there.

The only way to make your serializer somewhat covariant is to write

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

But the real question should be: What yre you trying to achieve? I feel, that your approach does not solve your problem.

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> {
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top