对于编码器,我具有以下接口(interface),该编码将Object编码为DataNode对象并返回:

public interface DataMarshaller<T> {

    /**
     * returns the actual class that this marshaller is capable of marshalling.
     * @return
     */
    Class<T> getDataClass();

    /**
     * marshalls the object to a DataNode
     *
     * @param object
     * @return
     */
    DataNode marshal(T object);

    /**
     * unmarshalls the object from a DataNode
     *
     * @param node
     * @return
     */
    T unMarshal(DataNode node);

}

为了确保能够为对象获取正确的编码器,我还具有Class<T> getDataClass()方法来返回其类(由于类型擦除,该类在编译后会丢失)。

现在,我想在一个能够编码(marshal)Octree<T>类型的对象的类中实现此接口(interface),如下所示:
public class OctreeMarshaller<T> implements DataMarshaller<Octree<T>> {

    @Override
    public Class<Octree<T>> getDataClass() {
        return Octree.class; //<- compiletime error
    }

    @Override
    public DataNode marshal(Octree<T> object) {
        //...
    }

    @Override
    public Octree<T> unMarshal(DataNode node) {
        //...
    }


}

我的问题是,(当然)Octree.class不是Class<Octree<T>>类型,而是非通用类型Class<Octree>,而Java不允许我将其强制转换为Class<Octree<T>>

现在的问题是:有没有比我已经考虑过的两种方法更优雅的解决方法:
  • 将接口(interface)中的返回值从Class<T>更改为Class<?>
  • OctreeMarshaller的类签名更改为public class OctreeMarshaller implements DataMarshaller<Octree>
  • 最佳答案

    没有Octree<T>实例,就不能构造Class<Octree<T>>类型的类对象。但是由于我们知道(由于类型擦除),在运行时只有一个类Octree,因此可以安全地编写

    public class OctreeMarshaller<T> implements DataMarshaller<Octree<T>> {
    
        @Override
        @SuppressWarnings("unchecked")
        public Class<Octree<T>> getDataClass() {
            return (Class<Octree<T>>)(Class<?>)Octree.class;
        }
    
        [...]
    }
    

    09-27 13:41