Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generics issue

im new to generics concept in java

In my application im using generics in one class, following is the my sample code

public class GPBFormat<T extends Message> implements IGPBFormat<T> {
@Override
public byte[] serialize(T t) 
{
    return t.toByteArray();
}
@Override
public T deSerialize(byte[] value) 
{
    T.parseFrom(value);
    return null;
}

im above code im using parseFrom method, but the problem is this method will exist only in concrete classes i.e which classes extends the Message class, so im unable to access parseFrom method with this generics. How can i solve this?

Thanks, R.Ramesh

like image 909
Rams Avatar asked Feb 26 '23 02:02

Rams


2 Answers

Pass in to the constructor(s) a factory object, along the lines of:

interface Parser<T extends Message> {
    T parseFrom(byte[] value);
}

If GPBFormat does little more than you've quoted, then perhaps it should be abstract and not delegate to a separate factory.

like image 64
Tom Hawtin - tackline Avatar answered Mar 09 '23 00:03

Tom Hawtin - tackline


Are these protocol buffers? Is your parseFrom method static?

If parseFrom is not static, you should do

@Override
public boolean deSerialize(T message, byte[] value) 
{
    // protocol messages return boolean whether parsing succeeded
    return message.newBuilderForType().mergeFrom(value).build();
}
like image 23
sjr Avatar answered Mar 09 '23 01:03

sjr