需要创建一个自定义类型的方法

Need to create a method with custom type

我有一个方法如下:

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

在这一行中,我想传递自定义类型。我怎样才能做到这一点? 例如:我想创建任何其他 class 类型的 Super。 我可以将任何可以在方法中的byte[]位置传递的参数传递给方法吗?

class SuperImpl 看起来像:

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

您必须创建一个泛型方法:

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

您可以这样称呼它:

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

不过,您必须确定一件事。

您必须确保 getData(object) returns T。如果这样做,此方法将编译。否则,如果 getData(object) always returns Object,你必须在 SuperImpl class 中提供一个构造函数消耗 Object.