How to interpret “public T readObjectData(… Class type)” in Java?

前端 未结 4 1093
不知归路
不知归路 2020-12-02 11:20

I have this Java code.

public  T readObjectData(ByteBuffer buffer, Class type) {
...
T retVal = (T) summaries;
return retVal;
4条回答
  •  盖世英雄少女心
    2020-12-02 11:39

    is a parameter class. There is no class named T. You can use this method with any class specified via second method argument named type.

    since method is defined as following:

    public T readObjectData(ByteBuffer buffer, Class type)

    You can call it as written below:

    MyClass obj = o.readObjectData(buffer, MyClass.class);

    Please pay attention that you do not have to cast return value of readOjectData() to MyClass. Once upon a time, before java 5 this method would be defined as:

    public Object readObjectData(ByteBuffer)

    and its usage looked like:

    MyClass obj = (MyClass)o.readObjectData(buffer);

    Since casting may cause ClassCastException this is a bad practice. This was a reason for invention of generics.

提交回复
热议问题