Nishant Lakhara
Nishant Lakhara

Reputation: 2445

Need to create a method with custom type

I have a method as mentioned below :

protected Super<?> generateSuper(Serializable object) throws IOException   {
        Object data = getData(object);
        Super<Object> sup = new SuperImpl<Object>(data);
        return sup;
 }

On this line , I want to pass custom type. How can i do this? For example : I want to create Super of any other class type. Can I pass any argument to the method that can be passed at the place of byte[] in the method?

The class SuperImpl looks like :

public class SuperImpl<T> implements Super<T>{
    public SuperImpl(T data) {  
    }   
} 

Upvotes: 0

Views: 287

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You have to create a generic method:

protected <T> Super<T> generateSup(Serializable object) throws IOException {
    T data = getData(object); //questionable
    Super<T> sup = new SuperImpl<T>(data);
    return sup;
}

You will be able to call it like:

<byte[]>generateSup(object);
//or
<String>generateSup(anotherObject);
//or
<OtherClassType>generateSup(someOtherObject);

There's one thing you have to make sure, though.

You have to make sure that the getData(object) returns T. If you do, this method will compile. Otherwise, if the getData(object) always returns Object, you have to provide a constructor in the SuperImpl class that consumes a Object.

Upvotes: 1

Related Questions