0

I'd like to implement a custom deserialization object in Java 11. For this I have

public class ObjectDeserializer<T extends ObjectDeserializable> {
    public T deserialize(ByteBuffer buf)
    {
        T ret = instantiateNew();
        return (T) ret.deserialize(buf);
    }
}

How can I implement instantiateNew() method? Is it possible to create an instance of class using it's type ? What is the right way to do it?

Dmitry
  • 1,912
  • 2
  • 18
  • 29
  • Using reflection: You can obtain a reference to the class of `T`. With `Class` you can access the no argument constructor (provided the class has one) using `getConstructor()`. Finally you can call `newInstance()` to create a new instance. – Glains Jun 22 '20 at 09:51
  • Since generic types are erased at runtime, you need a reference to the class. Some mapping frameworks prefer it as an argument to the method, like ` T deserialize(ByteBuffer, Class)` – Glains Jun 22 '20 at 09:53

0 Answers0